HTTP
HyperText Transfer Protocol
A web communication protocol. Request-response model. GET, POST, PUT, DELETE methods. HTTPS is the encrypted version.
HyperText Transfer Protocol
A web communication protocol. Request-response model. GET, POST, PUT, DELETE methods. HTTPS is the encrypted version.
HTTP (HyperText Transfer Protocol) is an application-layer protocol for exchanging data between clients and servers on the web. It was developed in 1991 by Tim Berners-Lee together with the WWW (World Wide Web), and most internet traffic today is transmitted over HTTP. It works on a request-response model: when a web browser sends a request to a server, the server returns a response.
HTTP is a stateless protocol. Each request is independent, and the server does not remember previous requests. This characteristic makes it easy to scale servers, but cookies and sessions were introduced to support features such as maintaining login state. HTTP methods indicate the type of operation, and GET (read), POST (create), PUT (update), and DELETE (delete) are the most commonly used.
In HTTP/1.0, a new TCP connection was established for every request, but Keep-Alive was introduced in HTTP/1.1, making it possible to handle multiple requests over a single connection. HTTP/2 greatly improved performance by supporting multiplexing, header compression, server push, and more, and HTTP/3 reduced connection setup time by using the UDP-based QUIC protocol.
A status code indicates the result of a request. Typical examples are 200 (success), 301/302 (redirect), 400 (bad request), 401 (authentication required), 403 (forbidden), 404 (not found), and 500 (server error). In REST API design, using the correct status codes is essential for clients to handle errors appropriately. HTTPS is a version that adds TLS/SSL encryption, and on the modern web, HTTPS is the standard.
import requests
# GET 요청 - 데이터 조회
response = requests.get("https://api.github.com/users/octocat")
print(f"Status: {response.status_code}") # 200
print(f"Content-Type: {response.headers['Content-Type']}")
data = response.json()
print(f"Username: {data['login']}")
# POST 요청 - 데이터 생성
payload = {"title": "New Post", "body": "Hello World", "userId": 1}
response = requests.post(
"https://jsonplaceholder.typicode.com/posts",
json=payload,
headers={"Content-Type": "application/json"}
)
print(f"Created ID: {response.json()['id']}") # 101
# PUT 요청 - 데이터 수정
response = requests.put(
"https://jsonplaceholder.typicode.com/posts/1",
json={"title": "Updated Title", "body": "Updated Body", "userId": 1}
)
# DELETE 요청 - 데이터 삭제
response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
print(f"Deleted: {response.status_code == 200}")
# 헤더 설정 & 인증
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"User-Agent": "MyApp/1.0",
"Accept": "application/json"
}
response = requests.get("https://api.example.com/data", headers=headers)
# 타임아웃 & 에러 처리
try:
response = requests.get("https://api.example.com", timeout=5)
response.raise_for_status() # 4xx, 5xx 에러 시 예외 발생
except requests.exceptions.Timeout:
print("Request timed out")
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e.response.status_code}")
# GET 요청 - 기본
curl https://api.github.com/users/octocat
# GET 요청 - 응답 헤더 포함
curl -i https://api.github.com/users/octocat
# GET 요청 - 상태 코드만 확인
curl -s -o /dev/null -w "%{http_code}" https://google.com
# POST 요청 - JSON 데이터
curl -X POST https://jsonplaceholder.typicode.com/posts \
-H "Content-Type: application/json" \
-d '{"title": "New Post", "body": "Hello", "userId": 1}'
# PUT 요청 - 데이터 수정
curl -X PUT https://jsonplaceholder.typicode.com/posts/1 \
-H "Content-Type: application/json" \
-d '{"title": "Updated", "body": "Changed", "userId": 1}'
# DELETE 요청
curl -X DELETE https://jsonplaceholder.typicode.com/posts/1
# 인증 헤더 추가
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com
# 쿠키 저장 & 사용 (세션 유지)
curl -c cookies.txt https://example.com/login # 쿠키 저장
curl -b cookies.txt https://example.com/dashboard # 쿠키 사용
# 응답 시간 측정
curl -w "Time: %{time_total}s\n" -o /dev/null -s https://google.com
# HTTP/2 강제 사용
curl --http2 https://www.google.com
# 상세 디버깅 (요청/응답 헤더 전체)
curl -v https://api.github.com/users/octocat
# CORS 프리플라이트 요청 시뮬레이션
curl -X OPTIONS https://api.example.com \
-H "Origin: https://mysite.com" \
-H "Access-Control-Request-Method: POST" -v
// Fetch API - GET 요청
const response = await fetch('https://api.github.com/users/octocat');
const data = await response.json();
console.log(`Username: ${data.login}`);
console.log(`Status: ${response.status}`); // 200
// Fetch API - POST 요청
const postResponse = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({
title: 'New Post',
body: 'Hello World',
userId: 1
})
});
const created = await postResponse.json();
console.log(`Created ID: ${created.id}`);
// PUT & DELETE 요청
await fetch('/api/posts/1', { method: 'PUT', body: JSON.stringify(data) });
await fetch('/api/posts/1', { method: 'DELETE' });
// 에러 처리 패턴
async function fetchWithErrorHandling(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (error.name === 'TypeError') {
console.error('Network error or CORS issue');
}
throw error;
}
}
// Axios (더 편리한 HTTP 클라이언트)
import axios from 'axios';
// 인스턴스 생성 (기본 설정)
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: { 'Authorization': 'Bearer TOKEN' }
});
// 인터셉터 (요청/응답 가로채기)
api.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// 토큰 갱신 로직
return refreshTokenAndRetry(error.config);
}
return Promise.reject(error);
}
);
"Using POST for a delete API is confusing. It would be better to change it to RESTful DELETE /users/{id} and return 204 No Content on success. If it's a soft delete, it's also fine to return the deleted resource along with 200."
"The CORS error occurs because the server hasn't set the Access-Control-Allow-Origin header. In the development environment, work around it with a proxy, and in production, ask the backend team to add the origin to the whitelist. You also need to allow the preflight OPTIONS request."
"Right now it's HTTP/1.1, but if we upgrade to HTTP/2, multiplexing means that even when multiple APIs are requested at the same time, they are handled over a single TCP connection. Also, caching static resources with the Cache-Control header can reduce server load by more than 70%."
Query parameters of a GET request are exposed in the URL and remain in server logs and browser history. Always send sensitive information such as passwords and tokens in the POST body or the Authorization header.
If you return 200 even on errors and put only an error message in the body, the client cannot perform automatic retries or error handling. Distinguish precisely between 400 (bad request), 401 (authentication required), 404 (not found), and 500 (server error).
If you make requests without a timeout, the application will wait forever when the server does not respond. In general, set API requests to 5-30 seconds and file uploads to longer. Implement retry logic as well.
Use HTTPS without exception, choose appropriate HTTP methods and status codes, specify Content-Type, and configure timeouts and retries. During development, always check requests/responses with curl -v or the browser DevTools Network tab.