Python requests 에서 사용자 정의 헤더 설정 방법

PythonBeginner
지금 연습하기

소개

웹 개발 및 데이터 검색 분야에서 Python requests 에서 사용자 정의 헤더를 설정하는 방법을 이해하는 것은 매우 중요한 기술입니다. 이 튜토리얼에서는 Python requests 에 사용자 정의 헤더를 추가하는 과정을 안내하여 웹 스크래핑, API 상호 작용 등 다양한 가능성을 열어줍니다.

사용자 정의 헤더를 사용하면 웹 서버 및 API 에서 요청을 처리하는 방식을 제어할 수 있습니다. 요청을 인증하고, 콘텐츠 유형을 지정하고, 캐싱을 관리하고, 브라우저 동작을 모방하는 데 도움이 될 수 있습니다. 이 튜토리얼을 마치면 특정 요구 사항을 충족하도록 HTTP 요청을 사용자 정의하는 실질적인 지식을 얻게 될 것입니다.

HTTP 헤더 및 Requests 라이브러리 이해

코드를 작성하기 전에 HTTP 헤더가 무엇이며 왜 중요한지 이해해 보겠습니다.

HTTP 헤더란 무엇인가요?

HTTP 헤더는 클라이언트와 서버 간의 요청 및 응답에서 전송되는 키 - 값 쌍입니다. 콘텐츠 유형, 인증 자격 증명 또는 클라이언트 정보와 같은 요청 또는 응답에 대한 추가 정보를 제공합니다.

예를 들어, 웹사이트를 방문하면 브라우저는 자동으로 User-Agent (브라우저 식별), Accept (처리할 수 있는 콘텐츠 유형 지정) 등과 같은 헤더를 포함합니다.

Requests 라이브러리 설치

Python Requests 라이브러리는 HTTP 요청 작업을 간단하게 만들어줍니다. 환경에 설치되어 있는지 확인해 보겠습니다.

  1. WebIDE 에서 터미널을 열고 다음을 실행합니다.
pip install requests

requests 가 설치되거나 이미 설치되었음을 나타내는 출력을 볼 수 있습니다.

Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (2.28.1)
...

Requests 로 첫 번째 Python 스크립트 만들기

Requests 라이브러리를 테스트하기 위해 간단한 Python 스크립트를 만들어 보겠습니다.

  1. WebIDE 의 왼쪽 사이드바에서 탐색기 아이콘을 클릭합니다.
  2. 파일 탐색기에서 마우스 오른쪽 버튼을 클릭하고 "새 파일"을 선택합니다.
  3. 파일 이름을 test_requests.py로 지정합니다.
  4. 파일에 다음 코드를 추가합니다.
import requests

## Make a simple GET request to a test website
response = requests.get('https://httpbin.org/get')

## Print the response status code
print(f"Status Code: {response.status_code}")

## Print the response headers (what the server sent back)
print("\nResponse Headers:")
for header, value in response.headers.items():
    print(f"{header}: {value}")

## Print the response content
print("\nResponse Content:")
print(response.text[:300] + "...")  ## Showing just the first 300 characters
  1. 터미널을 열고 다음을 실행하여 스크립트를 실행합니다.
python test_requests.py

다음과 유사한 출력을 볼 수 있습니다.

Status Code: 200

Response Headers:
Date: Wed, 12 Apr 2023 10:15:23 GMT
Content-Type: application/json
Content-Length: 267
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Response Content:
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.28.1",
    "X-Amzn-Trace-Id": "Root=1-643..."
  },
  "origin": "123.45.67.89",
  "url": "https://httpbin.org/get"
}
...

이 출력은 다음을 보여줍니다.

  1. 서버가 상태 코드 200 (성공) 으로 응답했습니다.
  2. 서버가 다시 보낸 헤더
  3. 응답의 실제 내용 (JSON 형식)

서버가 Python requests 라이브러리에서 온 요청임을 식별하는 자동으로 생성된 User-Agent 헤더를 포함하여 우리로부터 받은 헤더를 기록하는 것을 확인하세요.

다음 단계에서는 이러한 헤더를 사용자 정의하여 요청을 더 효과적으로 제어하는 방법을 배우겠습니다.

Python Requests 에서 기본 사용자 정의 헤더 설정

HTTP 헤더가 무엇인지 이해하고 requests 라이브러리를 테스트했으므로 requests 에서 사용자 정의 헤더를 설정하는 방법을 알아보겠습니다.

사용자 정의 헤더를 설정하는 이유

사용자 정의 헤더를 설정해야 하는 몇 가지 이유가 있습니다.

  1. 인증 (Authentication): 많은 API 는 헤더에 전송된 인증 토큰을 필요로 합니다.
  2. User-Agent: 웹사이트에 자신을 식별하는 방식을 변경합니다.
  3. Content-Type: 전송하는 데이터의 형식을 지정합니다.
  4. Accept: 처리할 수 있는 콘텐츠 유형을 나타냅니다.
  5. Custom Headers: 일부 API 는 특정 사용자 정의 헤더를 필요로 합니다.

Requests 에서 헤더 설정

사용자 정의 헤더 설정을 연습하기 위해 새로운 Python 스크립트를 만들어 보겠습니다.

  1. WebIDE 에서 custom_headers.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
import requests

## Define the URL we'll make the request to
url = 'https://httpbin.org/headers'

## Define custom headers in a dictionary
custom_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'X-Custom-Header': 'Hello World',
    'Accept-Language': 'en-US,en;q=0.9'
}

## Make the request with our custom headers
response = requests.get(url, headers=custom_headers)

## Print the status code
print(f"Status Code: {response.status_code}")

## Print the response content (which shows the headers the server received)
print("\nHeaders received by server:")
print(response.json())
  1. 스크립트를 실행합니다.
python custom_headers.py

다음과 유사한 출력을 볼 수 있습니다.

Status Code: 200

Headers received by server:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'X-Custom-Header': 'Hello World', 'X-Amzn-Trace-Id': 'Root=1-6430a123-abc123def456'}}

무슨 일이 일어나고 있나요?

이 스크립트에서 우리는 다음을 수행했습니다.

  1. 세 개의 헤더를 포함하는 custom_headers라는 딕셔너리를 만들었습니다.

    • User-Agent: 기본 Python requests 값에서 웹 브라우저를 모방하도록 변경했습니다.
    • X-Custom-Header: 우리가 만든 완전히 사용자 정의된 헤더입니다.
    • Accept-Language: 콘텐츠에 대해 선호하는 언어를 지정합니다.
  2. headers 매개변수를 사용하여 requests.get()에 헤더를 전달했습니다.

  3. httpbin.org/headers의 응답은 정확히 어떤 헤더가 수신되었는지 보여주며, 사용자 정의 헤더가 성공적으로 전송되었음을 확인합니다.

특정 사용 사례에 맞게 헤더 수정

모바일 장치인 척하는 또 다른 예제를 만들어 보겠습니다. 이는 모바일 반응형 웹사이트를 테스트할 때 유용할 수 있습니다.

  1. mobile_headers.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
import requests

url = 'https://httpbin.org/headers'

## Header to simulate an iPhone
mobile_headers = {
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}

print("Making request with mobile device headers...")
response = requests.get(url, headers=mobile_headers)

## Print the response content
print(response.json())
  1. 스크립트를 실행합니다.
python mobile_headers.py

다음과 유사한 출력을 볼 수 있습니다.

Making request with mobile device headers...
{'headers': {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1', 'X-Amzn-Trace-Id': 'Root=1-6430a456-abc123def456'}}

이는 특정 User-Agent 헤더를 설정하여 서버에 iPhone 임을 성공적으로 알리고 있음을 보여줍니다.

인증 헤더 작업

사용자 정의 헤더의 가장 일반적인 용도 중 하나는 웹 서비스 및 API 를 사용한 인증입니다. 많은 API 는 요청 헤더에 인증 정보를 포함하도록 요구합니다.

인증 헤더 이해

몇 가지 일반적인 인증 방법이 있습니다.

  1. API 키 (API Keys): 헤더 또는 URL 매개변수에 포함된 간단한 토큰
  2. 기본 인증 (Basic Authentication): Base64 로 인코딩된 사용자 이름과 비밀번호
  3. Bearer 토큰 (Bearer Tokens): OAuth 및 JWT 인증에 사용
  4. 사용자 정의 인증 (Custom Authentication): 독점적인 인증 방식

Python requests 로 이러한 인증 방법을 구현하는 방법을 살펴보겠습니다.

API 키 인증

많은 API 는 API 키를 사용하여 액세스를 허용합니다. 이러한 키는 일반적으로 헤더 또는 URL 매개변수에 포함됩니다.

  1. api_key_auth.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
import requests

url = 'https://httpbin.org/headers'

## Simulating an API key authentication
api_key = 'my_fake_api_key_12345'

## Add the API key to the headers
headers = {
    'X-API-Key': api_key,
    'User-Agent': 'My API Client/1.0'
}

## Make the request
response = requests.get(url, headers=headers)

## Print results
print(f"Status Code: {response.status_code}")
print("\nHeaders received by server:")
print(response.json())
  1. 스크립트를 실행합니다.
python api_key_auth.py

다음과 유사한 출력을 볼 수 있습니다.

Status Code: 200

Headers received by server:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'My API Client/1.0', 'X-API-Key': 'my_fake_api_key_12345', 'X-Amzn-Trace-Id': 'Root=1-6430a789-abc123def456'}}

이는 X-API-Key 헤더에 API 키를 성공적으로 전송했음을 확인합니다.

기본 인증

기본 인증은 base64 형식으로 인코딩된 사용자 이름과 비밀번호를 전송하는 것을 포함합니다. Requests 라이브러리는 이를 쉽게 만듭니다.

  1. basic_auth.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
import requests

## URL that requires basic authentication
url = 'https://httpbin.org/basic-auth/user/pass'

## Method 1: Using the auth parameter (recommended)
print("Method 1: Using the auth parameter")
response = requests.get(url, auth=('user', 'pass'))
print(f"Status Code: {response.status_code}")
print(response.json())

## Method 2: Setting the Authorization header manually
print("\nMethod 2: Setting the Authorization header manually")
import base64

## Create the basic auth string: "username:password" encoded in base64
auth_string = base64.b64encode('user:pass'.encode('utf-8')).decode('utf-8')
headers = {
    'Authorization': f'Basic {auth_string}'
}

response = requests.get(url, headers=headers)
print(f"Status Code: {response.status_code}")
print(response.json())
  1. 스크립트를 실행합니다.
python basic_auth.py

다음과 유사한 출력을 볼 수 있습니다.

Method 1: Using the auth parameter
Status Code: 200
{'authenticated': True, 'user': 'user'}

Method 2: Setting the Authorization header manually
Status Code: 200
{'authenticated': True, 'user': 'user'}

두 방법 모두 서비스에서 성공적으로 인증되었습니다.

  • 방법 1 은 내장된 auth 매개변수를 사용하며, 이는 더 편리합니다.
  • 방법 2 는 Authorization 헤더를 수동으로 생성하여 기본 인증이 "내부적으로" 어떻게 작동하는지 보여줍니다.

Bearer 토큰 인증

Bearer 토큰 인증은 일반적으로 OAuth 2.0 및 JWT 기반 시스템에서 사용됩니다.

  1. bearer_auth.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
import requests

url = 'https://httpbin.org/headers'

## Simulate a bearer token (in a real app this would come from an OAuth process)
bearer_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.Q6CM1qIQkXA_DqyJq9MI0-mnRRCRR3c0SIM-Nul5MZs'

## Add the Authorization header with the Bearer token
headers = {
    'Authorization': f'Bearer {bearer_token}'
}

## Make the request
response = requests.get(url, headers=headers)

## Print results
print(f"Status Code: {response.status_code}")
print("\nHeaders received by server:")
print(response.json())
  1. 스크립트를 실행합니다.
python bearer_auth.py

다음과 유사한 출력을 볼 수 있습니다.

Status Code: 200

Headers received by server:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.Q6CM1qIQkXA_DqyJq9MI0-mnRRCRR3c0SIM-Nul5MZs', 'Host': 'httpbin.org', 'X-Amzn-Trace-Id': 'Root=1-6430a901-abc123def456'}}

이는 Authorization 헤더에 포함된 Bearer 토큰으로 성공적인 요청을 보여줍니다.

Bearer 토큰은 일반적으로 OAuth 2.0 서버와의 성공적인 인증 프로세스 후에 얻지만, 이 예제에서는 시연 목적으로 샘플 토큰을 사용하고 있습니다.

실용적인 응용 프로그램 및 모범 사례

다양한 유형의 사용자 정의 헤더를 설정하는 방법을 배웠으므로 실제 시나리오에서 헤더를 사용하는 몇 가지 실용적인 응용 프로그램과 모범 사례를 살펴보겠습니다.

JSON 데이터 송수신

최신 API 를 사용할 때 JSON 은 가장 일반적인 데이터 형식입니다. JSON 요청에 대한 헤더를 올바르게 설정하는 방법을 살펴보겠습니다.

  1. json_requests.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
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']}")
  1. 스크립트를 실행합니다.
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 객체를 사용하면 시간을 절약하고 코드를 더 깔끔하게 만들 수 있습니다.

  1. session_headers.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
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())
  1. 스크립트를 실행합니다.
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'}}

세션을 사용하는 것은 다음과 같은 여러 가지 이유로 모범 사례입니다.

  1. 성능 향상 (연결 풀링 (connection pooling))
  2. 요청 간 일관된 헤더
  3. 자동 쿠키 처리
  4. 필요할 때 요청별 사용자 정의를 추가하는 기능

헤더 사용에 대한 모범 사례

마무리하기 위해 HTTP 헤더를 사용할 때 따라야 할 몇 가지 모범 사례가 있습니다.

  1. 동일한 도메인에 대한 여러 요청에 대해 Session 객체를 사용합니다.
  2. 전송하는 데이터에 대해 Content-Type 헤더를 올바르게 설정합니다.
  3. 인증을 적절하게 처리합니다. 가능한 경우 내장된 인증을 사용합니다.
  4. 민감한 정보를 안전하게 유지합니다. API 키 또는 토큰을 하드코딩하지 마십시오.
  5. 필요한 헤더에 대해 API 문서를 주의 깊게 따릅니다.

다음은 이러한 모범 사례를 보여주는 최종 예제입니다.

  1. best_practices.py라는 새 파일을 만듭니다.
  2. 다음 코드를 추가합니다.
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()
  1. 스크립트를 실행합니다.
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 요청을 하는 구조화된 접근 방식을 보여줍니다.

요약

이 튜토리얼에서는 효과적인 웹 통신 및 API 통합을 위한 필수 기술인 Python requests 에서 사용자 정의 헤더를 사용하는 방법을 배웠습니다.

이제 다음을 이해하게 되었습니다.

  • HTTP 헤더가 무엇이며 웹 요청에 중요한 이유
  • 개별 요청에 대한 사용자 정의 헤더 설정 방법
  • 헤더를 사용한 다양한 인증 방법 (API 키, 기본 인증 (Basic auth), Bearer 토큰 (Bearer tokens))
  • JSON 데이터 및 콘텐츠 유형 헤더를 올바르게 사용하는 방법
  • 세션 객체를 사용하여 헤더를 관리하는 모범 사례

이러한 기술을 통해 모든 웹 API 와 보다 효과적으로 상호 작용하고, 보호된 리소스에 액세스하며, 요청 처리 방식을 제어하고, 더 정교한 웹 애플리케이션을 구축할 수 있습니다.

Python 기술을 계속 개발하면서 헤더, 상태 코드 및 콘텐츠 유형과 같은 HTTP 기본 사항을 이해하면 웹 애플리케이션에서 문제를 해결하고 더 고급 기능을 구현하는 데 도움이 된다는 점을 기억하십시오.