Skip to main content
Send Web Request

How to Make an HTTP Request with Python

Python offers several ways to make HTTP requests. The most popular is the requests library—install with pip install requests. The standard library's urllib also works. For async code, use HTTPX.

GET request example

Making a GET request to fetch data with custom headers:

import requests

response = requests.get(
    "https://api.example.com/users",
    headers={"Accept": "application/json", "Authorization": "Bearer YOUR_TOKEN"}
)
data = response.json()

POST request example

Making a POST request to send JSON data:

import requests

response = requests.post(
    "https://api.example.com/users",
    headers={"Content-Type": "application/json"},
    json={"name": "John", "email": "john@example.com"}
)
print(response.status_code)

PUT request example

Replacing a resource with PUT:

response = requests.put(
    "https://api.example.com/users/123",
    headers={"Content-Type": "application/json"},
    json={"name": "John Updated", "email": "john.new@example.com"}
)

PATCH request example

Partially updating a resource with PATCH:

response = requests.patch(
    "https://api.example.com/users/123",
    headers={"Content-Type": "application/json"},
    json={"email": "john.updated@example.com"}
)

DELETE request example

Deleting a resource:

response = requests.delete(
    "https://api.example.com/users/123",
    headers={"Authorization": "Bearer YOUR_TOKEN"}
)

Error handling

Always check response.raise_for_status() to raise an exception on 4xx/5xx. Or check response.status_code manually. Handle connection errors with try/except requests.RequestException.

import requests

try:
    response = requests.get("https://api.example.com/users")
    response.raise_for_status()
    data = response.json()
except requests.RequestException as e:
    print(f"Request failed: {e}")
except ValueError:
    print("Invalid JSON response")

Async example

Using async/await for non-blocking requests:

import httpx

async def fetch_users():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.example.com/users")
        return response.json()

Try it in Send Web Request

Use requests.get/post/put/patch/delete with the same URL and headers. Or run curl commands in Send Web Request to test before writing Python.

Open Send Web Request

Other libraries you can try