API
Application Programming Interface
A communication specification between software. REST, GraphQL, and gRPC styles. Key to integrating external services.
Application Programming Interface
A communication specification between software. REST, GraphQL, and gRPC styles. Key to integrating external services.
An API (Application Programming Interface) is a set of rules and tools for interaction between pieces of software. For web APIs, a client sends an HTTP request to a server, and the server returns a response in JSON or XML format. Modern software uses APIs to bring in a variety of functions from external services, such as payments, authentication, and AI model calls.
API architectures fall broadly into REST, GraphQL, and gRPC. REST uses HTTP methods (GET, POST, PUT, DELETE) and is the most widely used. GraphQL lets clients request only the data they need, preventing over-fetching. gRPC uses Protocol Buffers for binary communication that delivers high performance, and is mainly used for communication between microservices.
In AI, APIs are central to model serving. AI companies such as OpenAI, Anthropic, and Google offer their models through APIs, and developers can integrate the latest AI capabilities into their applications without separate infrastructure. The OpenAI API handles tens of millions of requests per month and has become the standard way of delivering AI services.
The important principles in API design are consistency, versioning, and clear documentation. A good API should be intuitive for developers to understand and use. Operational aspects such as rate limiting, authentication, and error handling are also important, and standard documentation tools such as OpenAPI (Swagger) make API maintenance and collaboration easier.
"""
API 호출 예제 - OpenAI Chat Completions API
에러 처리, 재시도, 타임아웃을 포함한 프로덕션 패턴
"""
import os
import time
from openai import OpenAI
from tenacity import retry, stop_after_attempt, wait_exponential
# API 클라이언트 초기화
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
timeout=30.0, # 30초 타임아웃
max_retries=0 # tenacity로 직접 재시도 관리
)
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10)
)
def call_chat_api(messages: list, model: str = "gpt-4") -> dict:
"""
OpenAI Chat API 호출 (재시도 로직 포함)
Args:
messages: 대화 메시지 리스트
model: 사용할 모델 (기본값: gpt-4)
Returns:
API 응답 딕셔너리
"""
start_time = time.time()
try:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.7,
max_tokens=1000
)
latency = time.time() - start_time
return {
"success": True,
"content": response.choices[0].message.content,
"model": response.model,
"usage": {
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens,
"total_tokens": response.usage.total_tokens
},
"latency_ms": round(latency * 1000, 2)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
# 사용 예시
messages = [
{"role": "system", "content": "당신은 친절한 AI 어시스턴트입니다."},
{"role": "user", "content": "API란 무엇인지 한 문장으로 설명해주세요."}
]
result = call_chat_api(messages)
if result["success"]:
print(f"응답: {result['content']}")
print(f"모델: {result['model']}")
print(f"토큰 사용량: {result['usage']['total_tokens']}")
print(f"응답 시간: {result['latency_ms']}ms")
else:
print(f"오류 발생: {result['error_type']}")
print(f"오류 메시지: {result['error']}")
"The OpenAI API's rate limit is 3,500 requests per minute, but our expected traffic is 5,000 per minute. We need a structure that queues requests at the API Gateway and retries with exponential backoff in the service layer. If necessary, we can also ask OpenAI to raise the rate limit."
"There's no timeout set on this API call. If the external service doesn't respond, the thread will wait forever. Please set a timeout of at least 30 seconds and change it to return an appropriate fallback response on error."
"The response of the v1/users/{id} endpoint contains sensitive information. Let's minimize the API response fields and split any additional information into a separate endpoint. Also, we need to apply rate limiting and API key authentication to every endpoint."
Never hardcode API keys in code or commit them to Git. Use environment variables or a secrets management service (AWS Secrets Manager, HashiCorp Vault), and reissue the key immediately if it leaks.
When a 429 Too Many Requests error occurs, don't just retry blindly; check the Retry-After header. Apply exponential backoff and jitter to spread the load on the server.
If you depend heavily on an external API, your whole system goes down when that service fails. Implement the Circuit Breaker pattern, caching, and fallback logic so the service stays up even during a partial failure.