Какие знаешь заголовки в http запросе?
Комментарии (1)
Ответ сгенерирован нейросетью и может содержать ошибки
HTTP Заголовки (Headers)
HTTP заголовки — это метаинформация, передаваемая в каждом запросе и ответе. Они содержат информацию о содержимом, типе запроса, аутентификации и многом другом. За 10+ лет я работал с десятками заголовков в production.
Основные заголовки запроса
Content-Type — тип содержимого тела запроса:
import requests
# JSON
response = requests.post(
"https://api.example.com/users",
headers={"Content-Type": "application/json"},
json={"name": "John"}
)
# Form data
response = requests.post(
"https://api.example.com/users",
headers={"Content-Type": "application/x-www-form-urlencoded"},
data={"name": "John"}
)
# multipart (файлы)
response = requests.post(
"https://api.example.com/upload",
headers={"Content-Type": "multipart/form-data"},
files={"file": open("image.jpg", "rb")}
)
Authorization — аутентификационные данные:
# Bearer token (JWT)
headers = {"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}
# Basic auth
headers = {"Authorization": "Basic dXNlcjpwYXNz"}
# API Key
headers = {"Authorization": "ApiKey sk_live_12345678"}
Accept — какой формат ответа ожидается:
# JSON
headers = {"Accept": "application/json"}
# XML
headers = {"Accept": "application/xml"}
# Любой тип
headers = {"Accept": "*/*"}
User-Agent — информация о клиенте:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
# Или для API запросов
headers = {"User-Agent": "MyApp/1.0"}
Cache-Control — управление кешем:
headers = {"Cache-Control": "no-cache"}
headers = {"Cache-Control": "max-age=3600"}
headers = {"Cache-Control": "public, max-age=86400"}
Заголовки ответа
Content-Type — тип содержимого ответа:
response = requests.get("https://api.example.com/users")
print(response.headers["Content-Type"]) # application/json; charset=utf-8
Content-Length — размер тела ответа в байтах:
print(response.headers["Content-Length"]) # 1234
Set-Cookie — установка cookie для клиента:
# Сервер устанавливает cookie
headers = {
"Set-Cookie": "session_id=abc123; Path=/; HttpOnly; Secure"
}
Location — для редиректов (301, 302, 303, 307):
headers = {"Location": "/new-location"}
X-RateLimit-* — информация о rate limiting:
print(response.headers["X-RateLimit-Limit"]) # 100
print(response.headers["X-RateLimit-Remaining"]) # 85
print(response.headers["X-RateLimit-Reset"]) # 1234567890
Server — информация о сервере:
print(response.headers["Server"]) # nginx/1.19.0
Заголовки безопасности
CORS заголовки:
# На сервере (Flask/Django)
headers = {
"Access-Control-Allow-Origin": "https://example.com",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400"
}
Strict-Transport-Security — HTTPS only:
headers = {"Strict-Transport-Security": "max-age=31536000; includeSubDomains"}
X-Content-Type-Options — защита от MIME sniffing:
headers = {"X-Content-Type-Options": "nosniff"}
X-Frame-Options — защита от clickjacking:
headers = {"X-Frame-Options": "SAMEORIGIN"}
Content-Security-Policy — CSP политика:
headers = {"Content-Security-Policy": "default-src self; script-src self cdn.example.com"}
Пример полного запроса/ответа
import requests
url = "https://api.github.com/user"
headers = {
"Authorization": "token ghp_xxxxxxxxxxxx",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "MyApp/1.0",
"X-Custom-Header": "custom-value"
}
response = requests.get(url, headers=headers)
# Просмотр заголовков ответа
print(response.headers)
# Content-Type: application/json; charset=utf-8
# X-RateLimit-Limit: 60
# X-RateLimit-Remaining: 59
Работа с заголовками в Python
import requests
from requests.structures import CaseInsensitiveDict
# Requests автоматически нормализует заголовки
headers = CaseInsensitiveDict({"content-type": "application/json"})
print(headers["Content-Type"]) # application/json
# В FastAPI
from fastapi import FastAPI, Header
from typing import Optional
app = FastAPI()
@app.get("/")
async def read_root(
user_agent: Optional[str] = Header(None),
x_custom: Optional[str] = Header(None)
):
return {
"user_agent": user_agent,
"custom": x_custom
}
HTTP заголовки — критичная часть веб-протокола. Правильное использование заголовков обеспечивает безопасность, производительность и совместимость приложения.