Skip to content

Q&A · Answered

How to make HTTP requests in Python

asked 9 months, 1 week ago 1005 views 1 answer
9

What library should I use for making HTTP requests in Python and how do I use it?

1 Answer

One accepted
19

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Using requests library

import requests

# GET request
response = requests.get('https://api.example.com/data')
data = response.json()

# POST request with data
response = requests.post('https://api.example.com/submit',
    json={'name': 'John', 'email': 'john@example.com'},
    headers={'Authorization': 'Bearer token'}
)

# Handle errors
response.raise_for_status()  # Raises exception for 4xx/5xx

With error handling

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
except requests.RequestException as e:
    print(f"Request failed: {e}")

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.