Back to all snippets
Library/Python/Call API with requests
pythonbeginnerhttpapirequestsnetwork

How to implement Call API with requests in Python

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.

Code Snippet

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')

What is Call API with requests?

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.

How It Works

  1. 1`requests.get(url)` makes a GET request and returns a Response object
  2. 2`response.status_code` is the HTTP status (200, 404, 500, etc.)
  3. 3`response.json()` automatically parses JSON response body
  4. 4`response.headers` contains response metadata

Common Use Cases

  • API clients - Call third-party APIs (GitHub, Stripe, OpenAI, etc.)
  • Web scraping - Fetch HTML pages and parse them
  • Data collection - Aggregate data from multiple API endpoints
  • Integration testing - Make real HTTP requests in tests

Key Benefits

  • Simple, readable API compared to urllib
  • Automatic JSON parsing with .json()
  • Supports all HTTP methods (GET, POST, PUT, DELETE)
  • Built-in session management for connection pooling

Common Mistakes to Avoid

  • Not checking status_code — assume every request succeeds. Always check before parsing JSON.
  • Not setting timeouts — requests can hang indefinitely. Use `requests.get(url, timeout=5)`.
  • Hardcoding API keys in code — use environment variables or config files.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

How do I send POST requests with data?

Use `requests.post(url, json={"key": "value"})` for JSON or `data={...}` for form data.

How do I handle timeouts and retries?

Set `timeout=5` on the request. For retries, use `requests.adapters.HTTPAdapter` with `Retry` from `urllib3.util.retry`.

About This Python Code Snippet

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.

Tags: http, api, requests, network  | Language: python  | Difficulty: beginner  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.