실용적인 응용 프로그램 및 모범 사례
다양한 유형의 사용자 정의 헤더를 설정하는 방법을 배웠으므로 실제 시나리오에서 헤더를 사용하는 몇 가지 실용적인 응용 프로그램과 모범 사례를 살펴보겠습니다.
JSON 데이터 송수신
최신 API 를 사용할 때 JSON 은 가장 일반적인 데이터 형식입니다. JSON 요청에 대한 헤더를 올바르게 설정하는 방법을 살펴보겠습니다.
json_requests.py라는 새 파일을 만듭니다.
- 다음 코드를 추가합니다.
import requests
import json
url = 'https://httpbin.org/post' ## This endpoint accepts POST requests
## Data to send
data = {
'name': 'John Doe',
'email': 'john@example.com',
'message': 'Hello, world!'
}
## Set appropriate headers for JSON
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
## Method 1: Using the json parameter (recommended)
print("Method 1: Using the json parameter")
response = requests.post(url, json=data, headers=headers)
print(f"Status Code: {response.status_code}")
print(response.json()['headers']) ## Show the headers received
print(f"\nData sent (as received by server): {response.json()['json']}")
## Method 2: Manually converting to JSON
print("\nMethod 2: Manually converting to JSON")
json_data = json.dumps(data)
response = requests.post(url, data=json_data, headers=headers)
print(f"Status Code: {response.status_code}")
print(response.json()['headers']) ## Show the headers received
print(f"\nData sent (as received by server): {response.json()['json']}")
- 스크립트를 실행합니다.
python json_requests.py
다음과 유사한 출력을 볼 수 있습니다.
Method 1: Using the json parameter
Status Code: 200
{'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '72', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'X-Amzn-Trace-Id': 'Root=1-6430ab12-abc123def456'}
Data sent (as received by server): {'name': 'John Doe', 'email': 'john@example.com', 'message': 'Hello, world!'}
Method 2: Manually converting to JSON
Status Code: 200
{'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '72', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'X-Amzn-Trace-Id': 'Root=1-6430ab13-abc123def456'}
Data sent (as received by server): {'name': 'John Doe', 'email': 'john@example.com', 'message': 'Hello, world!'}
두 방법 모두 작동하지만, Method 1 이 더 편리합니다. Requests 라이브러리가 JSON 변환을 처리하기 때문입니다.
기본 헤더로 재사용 가능한 세션 생성
동일한 헤더로 여러 요청을 해야 하는 경우 Session 객체를 사용하면 시간을 절약하고 코드를 더 깔끔하게 만들 수 있습니다.
session_headers.py라는 새 파일을 만듭니다.
- 다음 코드를 추가합니다.
import requests
## Create a session object
session = requests.Session()
## Set default headers for all requests made with this session
session.headers.update({
'User-Agent': 'MyCustomApp/1.0',
'Accept-Language': 'en-US,en;q=0.9',
'X-API-Key': 'my_session_api_key'
})
## Make a request using the session - it will include our default headers
print("First request with session:")
response = session.get('https://httpbin.org/headers')
print(response.json())
## Add a custom header just for this request
print("\nSecond request with additional header:")
response = session.get('https://httpbin.org/headers',
headers={'X-Custom-Header': 'Just for this request'})
print(response.json())
## Original headers remain unchanged for future requests
print("\nThird request (original headers only):")
response = session.get('https://httpbin.org/headers')
print(response.json())
- 스크립트를 실행합니다.
python session_headers.py
다음과 유사한 출력을 볼 수 있습니다.
First request with session:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'MyCustomApp/1.0', 'X-API-Key': 'my_session_api_key', 'X-Amzn-Trace-Id': 'Root=1-6430ab45-abc123def456'}}
Second request with additional header:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'MyCustomApp/1.0', 'X-API-Key': 'my_session_api_key', 'X-Custom-Header': 'Just for this request', 'X-Amzn-Trace-Id': 'Root=1-6430ab46-abc123def456'}}
Third request (original headers only):
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'MyCustomApp/1.0', 'X-API-Key': 'my_session_api_key', 'X-Amzn-Trace-Id': 'Root=1-6430ab47-abc123def456'}}
세션을 사용하는 것은 다음과 같은 여러 가지 이유로 모범 사례입니다.
- 성능 향상 (연결 풀링 (connection pooling))
- 요청 간 일관된 헤더
- 자동 쿠키 처리
- 필요할 때 요청별 사용자 정의를 추가하는 기능
헤더 사용에 대한 모범 사례
마무리하기 위해 HTTP 헤더를 사용할 때 따라야 할 몇 가지 모범 사례가 있습니다.
- 동일한 도메인에 대한 여러 요청에 대해 Session 객체를 사용합니다.
- 전송하는 데이터에 대해 Content-Type 헤더를 올바르게 설정합니다.
- 인증을 적절하게 처리합니다. 가능한 경우 내장된 인증을 사용합니다.
- 민감한 정보를 안전하게 유지합니다. API 키 또는 토큰을 하드코딩하지 마십시오.
- 필요한 헤더에 대해 API 문서를 주의 깊게 따릅니다.
다음은 이러한 모범 사례를 보여주는 최종 예제입니다.
best_practices.py라는 새 파일을 만듭니다.
- 다음 코드를 추가합니다.
import requests
import os
## In a real application, get these from environment variables or a secure configuration
## For this example, we're keeping it simple
API_KEY = os.environ.get('API_KEY', 'default_api_key')
BASE_URL = 'https://httpbin.org'
def create_api_client():
"""Create a reusable session with default headers."""
session = requests.Session()
## Set common headers
session.headers.update({
'User-Agent': 'MyApp/1.0',
'X-API-Key': API_KEY,
'Accept': 'application/json'
})
return session
def get_data(client, endpoint):
"""Make a GET request to the specified endpoint."""
url = f"{BASE_URL}/{endpoint}"
response = client.get(url)
return response.json()
def post_data(client, endpoint, data):
"""Make a POST request with JSON data."""
url = f"{BASE_URL}/{endpoint}"
response = client.post(url, json=data)
return response.json()
## Usage example
def main():
## Create the API client
client = create_api_client()
## GET request example
print("Making GET request...")
get_response = get_data(client, 'headers')
print(f"Headers sent: {get_response['headers']}")
## POST request example
print("\nMaking POST request...")
data = {'name': 'John', 'age': 30}
post_response = post_data(client, 'post', data)
print(f"Data received by server: {post_response['json']}")
if __name__ == '__main__':
main()
- 스크립트를 실행합니다.
python best_practices.py
다음과 유사한 출력을 볼 수 있습니다.
Making GET request...
Headers sent: {'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'MyApp/1.0', 'X-API-Key': 'default_api_key', 'X-Amzn-Trace-Id': 'Root=1-6430ab78-abc123def456'}
Making POST request...
Data received by server: {'name': 'John', 'age': 30}
이 예제는 재사용 가능한 세션 생성, 코드를 함수로 구성, 하드코딩된 민감한 정보 방지와 같은 모범 사례를 따르면서 사용자 정의 헤더로 HTTP 요청을 하는 구조화된 접근 방식을 보여줍니다.