Skip to content

API 입문: 제로부터 이해하는 "프로그램 간의 대화"

🎯 핵심 질문

API란 무엇인가? 이건 마치 이런 질문과 같습니다: 레스토랑의 메뉴를 어떻게 디자인하면 손님이 한눈에 이해할 수 있을까? 웨이터는 어떻게 주문을 받아야 실수가 없을까? API가 해결하는 것은 "프로그램 간에 어떻게 대화하는가"의 문제입니다. 여러분은 코드를 작성하는 첫날부터 이미 API를 사용하고 있었지만, 그것을 인식하지 못했을 뿐입니다.


0. 초보자가 흔히 겪는 세 가지 혼란

혼란 1: API는 아주 고도화된 것인가?

많은 사람들이 API라고 하면 시니어 엔지니어만 이해할 수 있는 개념이라고 생각합니다. 사실 여러분은 이미 오래전부터 API를 사용해왔습니다:

python
len("hello")        # 이것이 Python이 제공하는 API
open("file.txt")    # 이것도 API
requests.get(url)   # 이것도 API

혼란 2: Web API와 일반 API의 차이는?

유형호출 대상통신 방식전형적 시나리오
함수 API로컬 코드함수 호출len(), open()
운영체제 API운영체제시스템 호출파일 읽기/쓰기, 프로세스 생성
Web API원격 서버HTTP 요청AI 모델 호출, 날씨 정보 조회

혼란 3: HTTP와 SDK 중 어느 것을 써야 하나?

python
# HTTP 방식: 모든 세부사항을 직접 처리
import requests
response = requests.post(
    "https://api.deepseek.com/v1/chat/completions",
    headers={"Authorization": "Bearer sk-xxx"},
    json={"model": "deepseek-chat", "messages": [...]}
)
result = response.json()["choices"][0]["message"]["content"]

# SDK 방식: 집사가 대신 처리
from openai import OpenAI
client = OpenAI(api_key="sk-xxx")
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[...]
)
result = response.choices[0].message.content

1. API의 본질: 플러그와 소켓

API(Application Programming Interface, 애플리케이션 프로그래밍 인터페이스)는 "프로그램 간의 대화 약속"입니다.

1.1 가전제품으로 비유하기

개념가전제품 비유API 대응
인터페이스소켓 형태함수 시그니처 / URL
입력전류 입력함수 파라미터 / 요청 본문
출력가전제품 작동반환값 / 응답 본문

1.2 세 가지 API 형태 비교

TargetLocal code library
CommunicationFunction call
LatencyNanoseconds
Typical scenariosData processing, file operations
Function API example
len("hello")           # returns 5
max([1, 5, 3])         # returns 5
open("file.txt").read() # reads a file

1.3 함수 API vs HTTP API의 차이

많은 초보자가 혼란스러워합니다: 함수 API와 HTTP API는 대체 어떤 차이가 있을까요? 문서를 볼 때 어떻게 구분해야 할까요?

📚 Function API vs HTTP APILocal calls vs network requests: how should you read the docs?
📦Function API
Call styleDirect function call
ParametersArguments inside parentheses
Return valueReturn value directly
Error handlingException or return value
Python example
# Call a built-in function
length = len("hello")      # returns 5

# Call a library function
import math
result = math.sqrt(16)     # returns 4.0

# Call a custom function
def add(a, b):
    return a + b
sum = add(3, 5)            # returns 8
VS
🌐HTTP API
Call styleNetwork request
ParametersURL / body / headers
Return valueJSON/XML response
Error handlingStatus code checks
HTTP request example
POST /v1/chat/completions HTTP/1.1
Host: api.deepseek.com
Authorization: Bearer sk-xxx
Content-Type: application/json

{
  "model": "deepseek-chat",
  "messages": [
    {"role": "user", "content": "Hello"}
  ]
}
Core point:A function API works locally; an HTTP API communicates remotely. Function docs focus on parameters and return values, while HTTP API docs focus on endpoint, authentication, and request/response formats.

1.4 다양한 유형의 API 문서 읽는 법

다양한 유형의 API 문서를 접할 때, 집중해야 할 포인트가 각각 다릅니다:

📋 How to Read Different Doc TypesFunction docs, REST API docs, and SDK docs each emphasize different things
Doc typeFunction docs
Best forUsing standard library or third-party functions
Difficulty⭐⭐
🔍 What to focus on
Function signatureParameter typesReturn valueExceptionsExample code
📝Doc example
### json.loads(s, *, cls=None, object_hook=None...)

Parse a JSON string into a Python object.

**Parameters:**
- s (str): JSON string to parse
- cls (JSONDecoder): Custom decoder class
- object_hook (callable): Optional conversion function

**Returns:**
- dict | list: Parsed Python object

**Raises:**
- JSONDecodeError: The string is invalid JSON

**Example:**
>>> import json
>>> json.loads('{"name": "Alice"}')
{'name': 'Alice'}
💡Reading tips
  • Read the function signature first to see what parameters are needed.
  • Check parameter types and whether each parameter is required.
  • Check the return type so later code can handle it correctly.
  • Notice possible exceptions and prepare error handling.
📊Quick comparison of three doc types
Item
Function docs
REST API docs
SDK docs
Core focus
Parameters, return values
Endpoint, request body
Initialization, method chain
Code example
Function call
HTTP request
Object method
Error handling
Exceptions/return values
Status codes
Exception objects
Read first
Function signature
Base URL + Auth
Quick Start
Reading advice:For function docs, read the signature. For API docs, read the request format. For SDK docs, read examples first. When stuck, look for Quick Start or Getting Started.

2. 완전한 API 호출 한 번

👇 직접 해보기: 아래 버튼을 클릭하여 완전한 API 요청-응답 흐름을 관찰하세요:

API Request Demo
// Click a command below to simulate API requests
>
💻ClientSends request
Waiting for request...
HTTP Request
🖥️ServerHandles request
Waiting...
HTTP Response
📦ResponseReturns result
Waiting for response...
💡 Click a command button to observe a complete API request-response flow.

2.1 API 호출의 네 단계

단계무슨 일이 일어나는가가전제품 비유
요청클라이언트가 서버에 요청 전송스위치 켜기
전송요청이 네트워크를 통해 서버로 전송전류가 전선을 통해 흐름
처리서버가 요청을 처리하고 데이터 반환가전제품 작동 시작
응답클라이언트가 반환된 결과를 수신 및 처리전구 빛남

2.2 레스토랑 비유

레스토랑 역할API 대응설명
메뉴API 문서주문할 수 있는 "요리"가 무엇인지 알려줌
웨이터HTTP 프로토콜표준화된 "대화 방식"
주방서버"주문"에 따라 요청 처리
서빙응답결과를 "손님"에게 반환

3. HTTP 메서드: "질문"하는 건가, "실행"하는 건가?

Web API를 호출할 때, 서버에 무엇을 하고 싶은지 알려야 합니다. 그것이 HTTP 메서드가 존재하는 이유입니다.

3.1 레스토랑 주문으로 이해하기

시나리오현실에서라면 어떻게 말하나요?해당 HTTP 메서드
오늘 어떤 요리가 있는지 알고 싶다"웨이터, 메뉴 좀 보여주세요"GET - 순수한 "질문", 데이터 변경 없음
궁보계정을 주문하고 싶다"궁보계정 하나 주세요"POST - 무언가를 "실행", 데이터 생성
요리를 바꾸고 싶다"궁보계정을 탕수육으로 바꿔주세요"PUT - 데이터 교체
맛을 조절하고 싶다"궁보계정에 땅콩 넣지 마세요"PATCH - 부분 수정
더 이상 원하지 않는다"됐습니다, 그 요리는 취소할게요"DELETE - 데이터 삭제
get
Read
Query data
Idempotent
post
Create
Add data
Not idempotent
put
Full update
Replace resource
Idempotent
patch
Partial update
Modify fields
Not idempotent
delete
Delete
Remove resource
Idempotent
getRead - Query data
Fetch resources from the server without changing data
Restaurant analogy:"Waiter, show me the menu"
GET /api/users           # fetch user list
GET /api/users/123       # fetch one user
GET /api/products?cat=phone  # query phone products

멱등성에 대하여

멱등성: 여러 번 실행해도 결과가 같은가?

  • 멱등한 조작 (GET/PUT/DELETE): 10번 눌러도 1번 누른 것과 결과가 같음
  • 멱등하지 않은 조작 (POST): 10번 누르면 10개의 주문이 생성될 수 있음

해결 방안: POST 조작에 고유 ID 검증을 사용하여 중복 처리 방지.

3.2 HTTP 메서드 빠른 참조표

메서드용도멱등성안전성전형적 시나리오
GET리소스 조회목록 조회, 상세 보기
POST리소스 생성아니오아니오사용자 추가, 주문 제출
PUT전체 업데이트아니오전체 사용자 프로필 교체
PATCH부분 업데이트아니오아니오닉네임만 수정
DELETE리소스 삭제아니오사용자 삭제, 주문 취소

4. HTTP 상태 코드: 서버가 무엇을 말하고 있는 걸까?

서버가 응답할 때, 먼저 상태 코드를 반환하여 요청이 성공했는지 알려줍니다.

4.1 상태 코드 분류

2xxSuccess
The request was received, understood, and processed successfully
200 OK201 Created204 No Content
3xxRedirect
More action is needed to complete the request
301 Moved Permanently304 Not Modified307 Temporary Redirect
4xxClient error
The request has an error or cannot be completed
400 Bad Request401 Unauthorized403 Forbidden404 Not Found
5xxServer error
The server failed to handle a valid request
500 Internal Error502 Bad Gateway503 Unavailable
💡Memory tip:2️⃣ Success3️⃣ Redirect4️⃣ Client error5️⃣ Server error

4.2 자주 사용하는 상태 코드 상세 설명

상태 코드의미전형적 시나리오클라이언트 처리
200 OK성공요청이 정상적으로 처리됨데이터 표시
201 Created생성 성공POST 요청이 리소스 생성에 성공새 리소스로 이동
400 Bad Request요청 형식 오류파라미터 누락 또는 형식 불일치파라미터 확인
401 Unauthorized인증되지 않음유효한 API Key가 제공되지 않음사용자 로그인 유도
403 Forbidden권한 없음API Key에 해당 리소스 접근 권한이 없음권한 부족 안내
404 Not Found존재하지 않음요청한 주소나 리소스가 존재하지 않음URL 확인
429 Too Many Requests요청 과다속도 제한 초과나중에 재시도
500 Internal Server Error서버 오류서버 측 문제 발생사용자에게 나중에 재시도 안내

👇 직접 해보기: 아래 버튼을 클릭하여 일반적인 상태 코드의 의미를 알아보세요:

HTTP Status Code Demo
// Click a button to inspect status code meanings
>
2xx Success
200OKRequest succeeded
201CreatedResource created
204No ContentSucceeded with no response body
⚠️4xx Client errors
400Bad RequestMalformed request
401UnauthorizedNot authenticated
403ForbiddenNo permission
404Not FoundResource missing
422UnprocessableSemantic validation error
429Too ManyToo many requests
🔴5xx Server errors
500Server ErrorInternal server error
502Bad GatewayGateway error
503UnavailableService unavailable
💡 Click a command button to learn common HTTP status codes.

5. HTTP vs SDK: 직접 심부름할까, 집사에게 맡길까?

5.1 두 가지 호출 방식 비교

🏃 HTTP API🤵 SDK
비유직접 심부름집사 대행
장점✓ 모든 언어에서 사용 가능
✓ 요청 세부사항 완전 제어
✓ 추가 종속성 불필요
✓ 코드가 간결하고 읽기 쉬움
✓ 인증 자동 처리
✓ 내장 에러 재시도
단점✗ 모든 세부사항을 직접 처리
✗ 코드가 길고 오류 발생 가능
✗ 종속성 설치 필요
✗ 버전 문제 발생 가능
코드 예시requests.post(url, json=..., headers={...})client.chat.completions.create(...)

5.2 어떻게 선택할까?

시나리오추천 방식이유
빠른 개발SDK인증, 에러, 재시도 자동 처리
원리 학습HTTP기본 메커니즘 이해
지원하지 않는 언어HTTP모든 언어에서 사용 가능
커스터마이징 필요HTTP모든 세부사항을 유연하게 제어

💡 권장 사항

SDK를 사용할 수 있으면 SDK를 사용하세요, 번거로운 일은 라이브러리에 맡기고 시간은 본인을 위해 아끼세요.


6. API 문서를 어떻게 읽을까?

API 문서는 설명서와 메뉴를 결합한 것과 같습니다. 처음부터 끝까지 읽을 필요 없이, "사전 찾기" 방법만 배우면 됩니다.

6.1 문서 읽기 체크리스트

아무 API 문서(예: OpenAI나 DeepSeek)를 열면, 다음 몇 가지만 찾으면 됩니다:

📖API Document Translator
Base URL
https://api.deepseek.com
Endpoint
POST /v1/chat/completions
Headers
Authorization: Bearer sk-xxx
Content-Type: application/json
Body parameters
modelRequiredModel name
messagesRequiredConversation messages
temperatureOptional0-2, default 1
Translate into code
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://api.deepseek.com"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Hello"}]
)
Core idea:When reading docs, find three things: address (Base URL), authentication (Authorization), and parameters.
항목설명예시
Base URLAPI의 루트 주소https://api.deepseek.com
Authentication신원 증명 방법Authorization: Bearer sk-xxx
Endpoints구체적인 인터페이스 목록/v1/chat/completions
Parameters필수/선택 파라미터model(필수), temperature(선택)
Response반환 데이터 구조{"choices": [...]}

6.2 문서 읽기 단계

  1. Base URL 찾기 - 모든 요청의 접두사
  2. 인증 방식 이해 - API Key가 Header에 들어가는지 Query에 들어가는지?
  3. 필요한 Endpoint 찾기 - 호출할 구체적인 인터페이스
  4. 요청 파라미터 확인 - 어느 것이 필수이고 어느 것이 선택인지?
  5. 반환 형식 이해 - 데이터가 어떻게 구성되어 있는지?

7. 실습: API 호출 시뮬레이션

백 마디 말보다 한 번 실천이 낫습니다. 여기 시뮬레이션 API가 있으니, 파라미터를 자유롭게 입력하고 주소를 마음대로 바꿔보세요.

🧪API PlaygroundTry calls without touching a real server
Send a request to see the response
Quick tries:

다음 시나리오를 시도해 보세요:

  • 성공적인 요청: 올바른 Endpoint과 API Key 입력
  • 401 에러: API Key를 입력하지 않고, 서버가 어떻게 거부하는지 확인
  • 404 에러: 존재하지 않는 주소 입력

8. 요약

핵심 포인트

  1. API는 확성기입니다, 다른 코드나 원격 서버에 말을 전해줍니다
  2. 여러분은 이미 API를 사용해왔습니다, len()부터 open()까지 모두 API입니다
  3. Web API는 초능력입니다, 수천 리 떨어진 슈퍼컴퓨터를 호출할 수 있게 해줍니다
  4. SDK는 훌륭한 집사입니다, SDK를 사용할 수 있으면 직접 심부름하지 마세요
  5. 문서에서 세 가지만 찾으세요: 주소, 인증, 파라미터

AI 프로그래밍 시대에, 여러분은 이 핵심 개념들만 기억하면 됩니다. 나머지 세부사항은 IDE와 AI 어시스턴트가 처리해 줄 것입니다.


용어 빠른 참조표

용어전체 명칭설명
APIApplication Programming Interface소프트웨어 간의 상호작용 방법을 정의하는 애플리케이션 프로그래밍 인터페이스
Web API-HTTP 프로토콜 기반의 API로, 네트워크 통신에 사용
Endpoint-엔드포인트, API의 구체적인 주소
HTTPHyperText Transfer ProtocolWeb API가 사용하는 통신 프로토콜
GET-리소스를 조회하는 메서드
POST-데이터를 제출하는 메서드
SDKSoftware Development Kit소프트웨어 개발 키트로, 하위 수준 API 호출을 캡슐화
URLUniform Resource LocatorAPI의 네트워크 주소
JSONJavaScript Object Notation자주 사용되는 데이터 형식
Authentication-신원 확인 프로세스
Status Code-HTTP 응답의 상태 코드
Request-요청
Response-응답
Header-HTTP 헤더, 메타 정보 포함
Payload-요청이나 응답의 실제 데이터
Rate Limit-속도 제한
Idempotent-멱등성, 여러 번 실행해도 결과가 동일함
RESTRepresentational State TransferAPI 아키텍처 스타일의 일종
RPCRemote Procedure Call원격 프로시저 호출
GraphQL-쿼리 언어 API의 일종
gRPC-Google이 개발한 고성능 RPC 프레임워크