Make HTTP requests to APIs and handle responses in Python
Quick Answer
`requests.get(url)` returns a response object; check `response.status_code` and call `.json()` to parse the response body.
1import requests
2from typing import Any
3
4# Simple GET request
5response = requests.get('https://api.github.com/users/github')
6if response.status_code == 200:
7 data = response.json()
8 print(data['name'])
9else:
10 print(f"Error: {response.status_code}")
11
12# GET with parameters
13params = {"q": "python", "sort": "stars"}
14response = requests.get('https://api.github.com/search/repositories', params=params)
15print(response.url) # Shows full URL with params
16
17# POST request with JSON
18payload = {"name": "My App", "description": "Test"}
19response = requests.post('https://api.example.com/apps', json=payload)
20
21# With headers and timeout
22headers = {"Authorization": "Bearer token"}
23response = requests.get(
24 'https://api.example.com/data',
25 headers=headers,
26 timeout=5
27)
28
29# Session for multiple requests
30with requests.Session() as session:
31 session.headers.update({"Authorization": "Bearer token"})
32 response1 = session.get('https://api.example.com/endpoint1')
33 response2 = session.get('https://api.example.com/endpoint2')The `requests` library is the standard way to make HTTP requests in Python. It handles connection pooling, redirects, and encoding automatically. This snippet covers GET requests, JSON parsing, error handling, and common patterns.
Use `requests.post(url, json={"key": "value"})` for JSON or `data={...}` for form data.
Set `timeout=5` on the request. For retries, use `requests.adapters.HTTPAdapter` with `Retry` from `urllib3.util.retry`.
This free python code snippet for call api with requests is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement call api with requests quickly and correctly.
All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.