Python Requests 라이브러리: Python에서 HTTP 요청을 위한 완전 가이드
Updated on
Python에서 내장 urllib 모듈로 HTTP 요청을 만드는 일은 악명 높을 정도로 복잡하고 장황합니다. 파라미터를 수동으로 인코딩해야 하고, 여러 메서드 호출로 Response 객체를 다뤄야 하며, 간단한 API 요청 하나 보내는 데도 수십 줄의 보일러플레이트 코드를 작성해야 합니다. 이런 복잡성은 개발 속도를 늦추고 코드 유지보수를 더 어렵게 만듭니다.
Python requests 라이브러리는 HTTP 통신을 위한 우아하고 사람 친화적인 API를 제공해 이런 불편을 없애줍니다. REST API를 호출하든, 웹사이트를 스크래핑하든, 파일을 업로드하든, 자동화 스크립트를 만들든, requests 라이브러리를 사용하면 몇 줄의 코드만으로 HTTP 작업을 직관적이고 간단하게 처리할 수 있습니다.
이 종합 가이드에서는 기본 GET/POST 요청부터 인증, 세션, 에러 처리, 그리고 실제 API 통합 패턴까지 모두 배우게 됩니다.
Python Requests 라이브러리 설치하기
requests 라이브러리는 Python 표준 라이브러리에 포함되어 있지 않으므로, pip로 별도 설치가 필요합니다:
pip install requestsconda 사용자의 경우:
conda install requests설치가 끝나면 Python 스크립트에서 import 할 수 있습니다:
import requests설치 확인 및 버전 확인:
import requests
print(requests.__version__)Python Requests로 GET 요청 보내기
GET 요청은 서버에서 데이터를 가져오는 데 사용하는 가장 흔한 HTTP 메서드입니다. requests 라이브러리는 GET 요청을 매우 간단하게 만들어 줍니다.
기본 GET 요청
기본 GET 요청은 다음과 같습니다:
import requests
response = requests.get('https://api.github.com')
print(response.status_code) # 200
print(response.text) # Response body as string쿼리 파라미터(Query Parameters)를 포함한 GET 요청
쿼리 문자열을 포함한 URL을 수동으로 조립하는 대신 params 인자를 사용하세요:
import requests
# Method 1: Using params dictionary
params = {
'q': 'python requests',
'sort': 'stars',
'order': 'desc'
}
response = requests.get('https://api.github.com/search/repositories', params=params)
# The URL is automatically constructed:
# https://api.github.com/search/repositories?q=python+requests&sort=stars&order=desc
print(response.url) # View the constructed URL
data = response.json() # Parse JSON response커스텀 헤더(Custom Headers)를 포함한 GET 요청
많은 API는 인증이나 콘텐츠 협상(content negotiation)을 위해 커스텀 헤더가 필요합니다:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.9'
}
response = requests.get('https://api.example.com/data', headers=headers)
print(response.json())Python에서 POST 요청 보내기
POST 요청은 서버로 데이터를 전송하며, 주로 폼 제출이나 API 작업에 사용됩니다.
폼 데이터(Form Data)로 POST 요청 보내기
폼 인코딩 데이터(HTML 폼 제출과 같은)를 전송하려면:
import requests
# Send form data
data = {
'username': 'john_doe',
'password': 'secret123',
'remember_me': True
}
response = requests.post('https://example.com/login', data=data)
print(response.status_code)JSON 페이로드(JSON Payload)로 POST 요청 보내기
현대적인 REST API는 보통 JSON 페이로드를 기대합니다. requests 라이브러리는 JSON 직렬화를 자동으로 처리합니다:
import requests
# Method 1: Using json parameter (recommended)
payload = {
'name': 'New Project',
'description': 'A test project',
'tags': ['python', 'api']
}
response = requests.post('https://api.example.com/projects', json=payload)
# Method 2: Manual JSON encoding
import json
headers = {'Content-Type': 'application/json'}
response = requests.post(
'https://api.example.com/projects',
data=json.dumps(payload),
headers=headers
)파일을 포함한 POST 요청
files 인자로 파일을 업로드할 수 있습니다:
import requests
# Upload a single file
files = {'file': open('report.pdf', 'rb')}
response = requests.post('https://example.com/upload', files=files)
# Upload multiple files
files = {
'file1': open('document.pdf', 'rb'),
'file2': open('image.jpg', 'rb')
}
response = requests.post('https://example.com/upload', files=files)
# Upload file with additional form data
files = {'file': open('data.csv', 'rb')}
data = {'description': 'Monthly report', 'category': 'finance'}
response = requests.post('https://example.com/upload', files=files, data=data)기타 HTTP 메서드: PUT, PATCH, DELETE
requests 라이브러리는 모든 표준 HTTP 메서드를 지원합니다:
import requests
# PUT - Replace entire resource
data = {'name': 'Updated Name', 'status': 'active'}
response = requests.put('https://api.example.com/users/123', json=data)
# PATCH - Partially update resource
data = {'status': 'inactive'}
response = requests.patch('https://api.example.com/users/123', json=data)
# DELETE - Remove resource
response = requests.delete('https://api.example.com/users/123')
print(response.status_code) # 204 No Content
# HEAD - Get headers only (no response body)
response = requests.head('https://example.com')
print(response.headers)
# OPTIONS - Get supported methods
response = requests.options('https://api.example.com/users')
print(response.headers.get('Allow'))Response 객체 이해하기
Response 객체에는 서버 응답에 대한 모든 정보가 들어 있습니다:
import requests
response = requests.get('https://api.github.com/users/github')
# Status code
print(response.status_code) # 200, 404, 500, etc.
# Response body as string
print(response.text)
# Response body as JSON (for JSON APIs)
data = response.json()
print(data['login'])
# Raw binary content (for images, files)
image_data = response.content
with open('profile.jpg', 'wb') as f:
f.write(image_data)
# Response headers
print(response.headers)
print(response.headers['Content-Type'])
# Encoding
print(response.encoding) # 'utf-8'
# Request information
print(response.request.headers)
print(response.request.url)
# Check if request was successful
if response.ok: # True if status_code < 400
print("Success!")Request 헤더 다루기
헤더는 요청에 대한 중요한 메타데이터를 전달합니다.
커스텀 헤더 설정하기
import requests
headers = {
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Custom-Header': 'custom-value'
}
response = requests.get('https://api.example.com', headers=headers)Response 헤더 접근하기
import requests
response = requests.get('https://api.github.com')
# Dictionary-like access
print(response.headers['Content-Type'])
print(response.headers.get('X-RateLimit-Remaining'))
# Case-insensitive access
print(response.headers['content-type']) # Works!
# Iterate all headers
for key, value in response.headers.items():
print(f"{key}: {value}")Python Requests로 인증(Authentication) 처리하기
requests 라이브러리는 여러 인증 방식을 지원합니다:
Basic 인증(Basic Authentication)
import requests
from requests.auth import HTTPBasicAuth
# Method 1: Using auth parameter (recommended)
response = requests.get(
'https://api.example.com/protected',
auth=('username', 'password')
)
# Method 2: Explicit HTTPBasicAuth
response = requests.get(
'https://api.example.com/protected',
auth=HTTPBasicAuth('username', 'password')
)
# Method 3: Manual header (not recommended)
import base64
credentials = base64.b64encode(b'username:password').decode('utf-8')
headers = {'Authorization': f'Basic {credentials}'}
response = requests.get('https://api.example.com/protected', headers=headers)Bearer 토큰 인증
JWT 토큰과 OAuth 2.0에서 흔히 사용됩니다:
import requests
token = 'your_access_token_here'
headers = {'Authorization': f'Bearer {token}'}
response = requests.get('https://api.example.com/user', headers=headers)API Key 인증
import requests
# Method 1: Query parameter
params = {'api_key': 'your_api_key_here'}
response = requests.get('https://api.example.com/data', params=params)
# Method 2: Custom header
headers = {'X-API-Key': 'your_api_key_here'}
response = requests.get('https://api.example.com/data', headers=headers)OAuth 2.0 인증
OAuth 2.0의 경우 requests-oauthlib 라이브러리를 사용하세요:
from requests_oauthlib import OAuth2Session
client_id = 'your_client_id'
client_secret = 'your_client_secret'
token_url = 'https://oauth.example.com/token'
oauth = OAuth2Session(client_id)
token = oauth.fetch_token(token_url, client_secret=client_secret)
# Make authenticated requests
response = oauth.get('https://api.example.com/protected')지속 연결을 위한 세션(Sessions)
세션은 여러 요청에 걸쳐 쿠키, 커넥션 풀링, 설정을 유지합니다:
import requests
# Create a session
session = requests.Session()
# Set headers for all requests in this session
session.headers.update({
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json'
})
# Login and session maintains cookies
login_data = {'username': 'john', 'password': 'secret'}
session.post('https://example.com/login', data=login_data)
# Subsequent requests use the session cookies
response1 = session.get('https://example.com/dashboard')
response2 = session.get('https://example.com/profile')
# Close the session
session.close()인증이 포함된 세션
import requests
session = requests.Session()
session.auth = ('username', 'password')
# All requests in this session use the authentication
response1 = session.get('https://api.example.com/users')
response2 = session.get('https://api.example.com/posts')세션 컨텍스트 매니저
import requests
with requests.Session() as session:
session.headers.update({'Authorization': 'Bearer token123'})
response1 = session.get('https://api.example.com/data')
response2 = session.post('https://api.example.com/data', json={'key': 'value'})
# Session automatically closed after with blockTimeout 및 재시도(Retry) 전략
요청이 무기한 멈추는 것을 방지하려면 항상 timeout을 설정하세요:
Timeout 설정하기
import requests
# Single timeout value (applies to both connect and read)
response = requests.get('https://api.example.com', timeout=5)
# Separate connect and read timeouts
response = requests.get('https://api.example.com', timeout=(3, 10))
# 3 seconds to establish connection, 10 seconds to read response
# No timeout (dangerous - may hang forever)
response = requests.get('https://api.example.com', timeout=None)재시도 로직 구현하기
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# Configure retry strategy
retry_strategy = Retry(
total=3, # Total number of retries
backoff_factor=1, # Wait 1, 2, 4 seconds between retries
status_forcelist=[429, 500, 502, 503, 504], # Retry on these status codes
allowed_methods=["HEAD", "GET", "OPTIONS", "POST"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount("http://", adapter)
session.mount("https://", adapter)
# Requests will automatically retry on failure
response = session.get('https://api.example.com/data')Python Requests에서 에러 처리하기
프로덕션 애플리케이션에서는 견고한 에러 처리가 필수입니다.
흔한 예외 처리하기
import requests
from requests.exceptions import (
ConnectionError,
Timeout,
HTTPError,
RequestException
)
try:
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # Raises HTTPError for 4xx/5xx status codes
data = response.json()
except ConnectionError:
print("Failed to connect to the server")
except Timeout:
print("Request timed out")
except HTTPError as e:
print(f"HTTP error occurred: {e}")
print(f"Status code: {e.response.status_code}")
except RequestException as e:
# Catches all requests exceptions
print(f"An error occurred: {e}")
except ValueError:
# JSON decoding error
print("Invalid JSON response")상태 코드(Status Codes) 확인하기
import requests
response = requests.get('https://api.example.com/data')
# Method 1: Manual check
if response.status_code == 200:
data = response.json()
elif response.status_code == 404:
print("Resource not found")
elif response.status_code >= 500:
print("Server error")
# Method 2: Using raise_for_status()
try:
response.raise_for_status()
data = response.json()
except requests.exceptions.HTTPError as e:
if response.status_code == 404:
print("Resource not found")
elif response.status_code == 401:
print("Authentication required")
else:
print(f"HTTP error: {e}")
# Method 3: Using response.ok
if response.ok: # True if status_code < 400
data = response.json()
else:
print(f"Request failed with status {response.status_code}")SSL 검증 및 인증서
기본적으로 requests는 SSL 인증서를 검증합니다:
import requests
# Default behavior - verify SSL certificate
response = requests.get('https://api.example.com')
# Disable SSL verification (not recommended for production)
response = requests.get('https://example.com', verify=False)
# Suppress the InsecureRequestWarning
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
response = requests.get('https://example.com', verify=False)
# Use custom CA bundle
response = requests.get('https://example.com', verify='/path/to/ca_bundle.crt')
# Client-side certificates
response = requests.get(
'https://example.com',
cert=('/path/to/client.crt', '/path/to/client.key')
)Python Requests에서 프록시(Proxies) 사용하기
요청에 프록시 서버를 설정할 수 있습니다:
import requests
# HTTP and HTTPS proxies
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get('https://api.example.com', proxies=proxies)
# SOCKS proxy (requires requests[socks])
proxies = {
'http': 'socks5://user:pass@host:port',
'https': 'socks5://user:pass@host:port'
}
# Use environment variables
# Set HTTP_PROXY and HTTPS_PROXY environment variables
response = requests.get('https://api.example.com') # Automatically uses env proxies
# Disable proxies
response = requests.get('https://api.example.com', proxies={'http': None, 'https': None})Python HTTP 라이브러리 비교
requests 라이브러리를 대안들과 비교하면 다음과 같습니다:
| Feature | requests | urllib | httpx | aiohttp |
|---|---|---|---|---|
| Ease of Use | Excellent (Pythonic API) | Poor (verbose) | Excellent | Good |
| Async Support | No | No | Yes | Yes |
| HTTP/2 Support | No | No | Yes | No |
| Session Management | Built-in | Manual | Built-in | Built-in |
| JSON Handling | Automatic | Manual | Automatic | Automatic |
| Connection Pooling | Yes | No | Yes | Yes |
| Standard Library | No (pip install) | Yes | No (pip install) | No (pip install) |
| Documentation | Excellent | Good | Excellent | Good |
| Performance | Good | Fair | Excellent | Excellent (async) |
| SSL/TLS | Full support | Full support | Full support | Full support |
| Best For | Synchronous HTTP, general use | Simple scripts, no dependencies | Modern sync/async HTTP | High-performance async |
각 라이브러리를 언제 사용할까:
- requests: 대부분의 동기(synchronous) HTTP 작업에 대한 기본 선택지. 웹 스크래핑, API 소비(호출), 일반적인 HTTP 작업에 적합합니다.
- urllib: 외부 패키지를 설치할 수 없고(표준 라이브러리만 사용해야 하는 경우) 의존성을 추가할 수 없을 때만 고려하세요.
- httpx: HTTP/2 지원이 필요하거나, async 기능을 갖춘 현대적인 requests 호환 API를 원할 때 적합합니다.
- aiohttp: 많은 동시 요청을 처리하는 고성능 비동기 애플리케이션에 적합합니다.
Rate Limiting과 예의 있는 스크래핑
웹사이트를 스크래핑하거나 API를 호출할 때는 rate limiting을 구현하세요:
import requests
import time
from datetime import datetime
class RateLimitedSession:
def __init__(self, requests_per_second=1):
self.session = requests.Session()
self.min_interval = 1.0 / requests_per_second
self.last_request_time = 0
def get(self, url, **kwargs):
# Wait if necessary
elapsed = time.time() - self.last_request_time
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
# Make request
response = self.session.get(url, **kwargs)
self.last_request_time = time.time()
return response
# Use rate-limited session
session = RateLimitedSession(requests_per_second=2) # 2 requests per second
urls = ['https://api.example.com/item/1', 'https://api.example.com/item/2']
for url in urls:
response = session.get(url)
print(f"{datetime.now()}: {response.status_code}")robots.txt 준수하기
import requests
from urllib.robotparser import RobotFileParser
def can_fetch(url, user_agent='MyBot'):
"""Check if URL can be scraped according to robots.txt"""
rp = RobotFileParser()
robots_url = f"{url.split('/')[0]}//{url.split('/')[2]}/robots.txt"
rp.set_url(robots_url)
rp.read()
return rp.can_fetch(user_agent, url)
url = 'https://example.com/page'
if can_fetch(url):
response = requests.get(url)
else:
print("Scraping not allowed by robots.txt")실제 예제와 활용 사례
예제 1: REST API 사용(소비)하기
import requests
class GitHubAPI:
def __init__(self, token=None):
self.base_url = 'https://api.github.com'
self.session = requests.Session()
if token:
self.session.headers.update({'Authorization': f'token {token}'})
def get_user(self, username):
"""Get user information"""
response = self.session.get(f'{self.base_url}/users/{username}')
response.raise_for_status()
return response.json()
def search_repositories(self, query, sort='stars', limit=10):
"""Search repositories"""
params = {'q': query, 'sort': sort, 'per_page': limit}
response = self.session.get(f'{self.base_url}/search/repositories', params=params)
response.raise_for_status()
return response.json()['items']
def create_issue(self, owner, repo, title, body):
"""Create an issue in a repository"""
url = f'{self.base_url}/repos/{owner}/{repo}/issues'
data = {'title': title, 'body': body}
response = self.session.post(url, json=data)
response.raise_for_status()
return response.json()
# Usage
api = GitHubAPI(token='your_github_token')
user = api.get_user('torvalds')
print(f"Name: {user['name']}, Followers: {user['followers']}")
repos = api.search_repositories('python requests', limit=5)
for repo in repos:
print(f"{repo['full_name']}: {repo['stargazers_count']} stars")예제 2: 진행 상황 표시와 함께 파일 다운로드하기
import requests
from tqdm import tqdm
def download_file(url, filename):
"""Download file with progress bar"""
response = requests.get(url, stream=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
with open(filename, 'wb') as f, tqdm(
desc=filename,
total=total_size,
unit='B',
unit_scale=True,
unit_divisor=1024,
) as progress_bar:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
progress_bar.update(len(chunk))
# Download a file
download_file('https://example.com/large-file.zip', 'downloaded.zip')예제 3: 에러 처리를 포함한 웹 스크래핑
import requests
from bs4 import BeautifulSoup
import time
def scrape_articles(base_url, max_pages=5):
"""Scrape article titles from a news website"""
session = requests.Session()
session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
articles = []
for page in range(1, max_pages + 1):
try:
url = f"{base_url}?page={page}"
response = session.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
titles = soup.find_all('h2', class_='article-title')
for title in titles:
articles.append({
'title': title.text.strip(),
'url': title.find('a')['href'] if title.find('a') else None
})
print(f"Scraped page {page}: {len(titles)} articles")
time.sleep(1) # Rate limiting
except requests.exceptions.RequestException as e:
print(f"Error scraping page {page}: {e}")
continue
return articles
# Usage
articles = scrape_articles('https://news.example.com/articles', max_pages=3)
print(f"Total articles collected: {len(articles)}")예제 4: 페이지네이션을 포함한 API 연동
import requests
def fetch_all_items(api_url, headers=None):
"""Fetch all items from a paginated API"""
items = []
page = 1
while True:
try:
params = {'page': page, 'per_page': 100}
response = requests.get(api_url, params=params, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
if not data: # No more items
break
items.extend(data)
print(f"Fetched page {page}: {len(data)} items")
page += 1
# Check for pagination in headers
if 'Link' in response.headers:
links = response.headers['Link']
if 'rel="next"' not in links:
break
except requests.exceptions.RequestException as e:
print(f"Error fetching page {page}: {e}")
break
return items
# Usage
all_items = fetch_all_items('https://api.example.com/items')
print(f"Total items: {len(all_items)}")Jupyter에서 RunCell로 API 테스트하기
API 연동을 개발하고 테스트할 때, RunCell (opens in a new tab)은 Jupyter 노트북 안에서 바로 사용할 수 있는 AI 기반 에이전트 환경을 제공합니다. HTTP 요청과 응답을 수동으로 디버깅하는 대신, RunCell의 지능형 에이전트가 다음을 도와줄 수 있습니다:
- 올바른 인증을 포함해 API 요청을 자동으로 구성하고 테스트
- 응답 파싱과 에러 처리를 실시간으로 디버깅
- 일반적인 HTTP 패턴을 위한 코드 스니펫 생성
- API 응답을 기대 스키마와 비교해 검증
- API 응답 데이터 변환을 빠르게 반복(iterate)
이는 여러 인증 단계, 페이지네이션 처리, 복잡한 데이터 파싱 로직이 필요한 API를 다룰 때 특히 유용합니다. RunCell은 HTTP 요청을 수동으로 테스트하는 과정에서 생기는 반복을 줄여 개발 워크플로를 가속화합니다.
FAQ
Python requests 라이브러리는 무엇에 사용되나요?
Python requests 라이브러리는 웹 서버와 API에 HTTP 요청을 보내는 데 사용됩니다. 웹 페이지 가져오기, REST API 호출, 폼 데이터 전송, 파일 업로드, 인증 처리 같은 작업을 단순화합니다. 직관적인 API와 폭넓은 기능 덕분에 Python에서 가장 인기 있는 HTTP 라이브러리입니다.
Python requests 라이브러리는 어떻게 설치하나요?
pip로 requests 라이브러리를 설치하세요: pip install requests. conda 환경에서는 conda install requests를 사용합니다. 설치 후 Python 코드에서 import requests로 불러오면 됩니다. requests는 Python 표준 라이브러리에 포함되어 있지 않으므로 설치가 필요합니다.
requests.get()과 requests.post()의 차이는 무엇인가요?
requests.get()은 서버의 데이터를 가져오며 서버 상태를 변경하지 않는 경우가 일반적이라 웹 페이지나 API 데이터를 조회할 때 사용됩니다. requests.post()는 서버에 데이터를 전송해 리소스를 생성하거나 업데이트하는 데 사용되며, 폼 제출, 파일 업로드, 서버 상태를 변경하는 API 작업에 흔히 쓰입니다. GET은 파라미터를 URL로 전달하고, POST는 데이터를 요청 바디에 담아 보냅니다.
Python requests 라이브러리에서 에러는 어떻게 처리하나요?
try-except 블록으로 요청 예외를 처리하세요. 네트워크 문제는 ConnectionError, 응답 지연은 Timeout, 4xx/5xx 상태 코드는 HTTPError, 그리고 RequestException은 포괄적인 예외 처리에 사용합니다. 각 요청 뒤에 response.raise_for_status()를 호출하면 실패한 요청에 대해 자동으로 HTTPError를 발생시킬 수 있습니다. 또한 요청이 무기한 대기하지 않도록 항상 timeout을 설정하세요.
Python requests로 JSON 데이터는 어떻게 전송하나요?
requests에서 json 인자를 사용하세요: requests.post(url, json=data). 라이브러리가 Python dict를 자동으로 JSON으로 직렬화하고 Content-Type: application/json 헤더도 설정합니다. JSON 응답 파싱은 response.json()을 사용하면 JSON 본문이 Python dict로 역직렬화됩니다.
Python에서는 requests와 urllib 중 무엇을 써야 하나요?
대부분의 HTTP 작업에는 requests 라이브러리를 사용하세요. urllib에 비해 API가 훨씬 깔끔하고, JSON 처리 자동화, 내장 세션 관리, 더 나은 에러 처리를 제공합니다. 외부 패키지를 설치할 수 없어 Python 표준 라이브러리만 써야 하는 경우에만 urllib를 고려하세요. HTTP/2나 async 지원이 필요한 현대적 애플리케이션이라면 대안으로 httpx를 고려할 수 있습니다.
Python requests에 인증을 추가하려면 어떻게 하나요?
Basic 인증은 requests.get(url, auth=('username', 'password'))를 사용합니다. Bearer 토큰(JWT, OAuth)은 Authorization 헤더를 추가하세요: headers = {'Authorization': f'Bearer {token}'}. API key는 params 딕셔너리로 쿼리 파라미터에 넣거나, 'X-API-Key' 같은 커스텀 헤더로 전달할 수 있습니다. 세션을 사용하면 여러 요청에 걸쳐 인증을 유지할 수 있습니다.
Python requests의 세션(session)이란 무엇이며 언제 사용하나요?
세션은 동일한 서버로 여러 번 요청할 때 설정(헤더, 쿠키, 인증)을 유지합니다. API에 여러 번 요청할 때, 쿠키로 로그인 상태를 유지해야 할 때, TCP 연결을 재사용해 성능을 높이고 싶을 때 세션을 사용하세요. session = requests.Session()으로 세션을 만들고, requests.get() 대신 session.get()을 사용하면 됩니다.
결론
Python requests 라이브러리는 Python에서 HTTP 통신을 위한 필수 도구입니다. 우아한 API 덕분에 복잡한 HTTP 작업도 단순하고 읽기 쉬운 코드로 바꿀 수 있습니다. 기본 GET 요청부터 인증, 세션, 파일 업로드, 에러 처리 같은 고급 기능까지, requests는 견고한 HTTP 상호작용에 필요한 모든 것을 제공합니다.
이 가이드의 패턴과 모범 사례(타임아웃 설정, 재시도 로직 구현, 우아한 에러 처리, rate limit 준수)를 익히면 웹 서비스 및 API와 효과적으로 통신하는 신뢰성 높은 애플리케이션을 만들 수 있습니다. REST API를 호출하든, 웹사이트를 스크래핑하든, 자동화 도구를 만들든, requests 라이브러리는 HTTP 작업을 간단하고 유지보수 가능하게 만들어 줍니다.