Browse Python Topics ▼
Pick a Web Framework

HTTP and REST APIs

📂 Databases, APIs & Optimization 📘 Lesson 56 of 57

Make HTTP requests to external web APIs, handle status codes, parse JSON payloads, and manage sessions using requests and httpx.

Modern software rarely works in isolation. An e-commerce store needs to process payments via Stripe, a weather app needs real-time radar data, and a machine learning service needs to fetch embeddings from an AI platform.

All of these systems communicate over the internet using HTTP (Hypertext Transfer Protocol) and REST APIs (Representational State Transfer).

While Python’s standard library includes urllib.request, writing raw urllib code is verbose and awkward. In modern Python, the industry standards for communicating with web services are requests (for synchronous code) and httpx (for modern synchronous and asynchronous asyncio code).


The Anatomy of an HTTP Request

Think of an HTTP request like ordering at a restaurant:

  1. You (the Client) send an order (Request) to the kitchen (Server).
  2. The waiter brings back your meal or an explanation (Response) along with a status note (Status Code).

Every HTTP request is composed of five key parts:

Method + URL:
GET https://api.example.com/v1/products?category=laptops&limit=10
 │                           │         └────────┬──────────────┘
 │                           │                  ▼
 │                           │           Query Parameters (filtering)
 │                           ▼
 │                   Endpoint / Resource Path
 ▼
HTTP Method (Action to perform)

Headers:
Accept: application/json
Authorization: Bearer secret_api_token_123

Body (Optional payload for POST/PUT):
{"name": "Pro Keyboard", "price": 129.99}

HTTP Methods (Verbs)

  • GET: Retrieve data. Safe and read-only. Calling it 1,000 times does not modify server data.
  • POST: Create a new resource (e.g. submit a payment, register an account).
  • PUT / PATCH: Update an existing resource (PUT replaces the entire record; PATCH updates specific fields).
  • DELETE: Remove an existing resource.

HTTP Status Code Families

When an API responds, it includes a three-digit Status Code indicating what happened:

Code RangeMeaningCommon Examples
2xxSuccess200 OK (Standard success), 201 Created (New item saved), 204 No Content
3xxRedirection301 Moved Permanently, 302 Found
4xxClient Error (You made a mistake)400 Bad Request, 401 Unauthorized (Missing login), 403 Forbidden (No permission), 404 Not Found, 429 Too Many Requests (Rate limit reached)
5xxServer Error (The remote server crashed)500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

Fetching Data with requests

First install the library:

pip install requests

1. Making a GET Request and Parsing JSON

Most modern APIs return data serialized in JSON (json-csv). The requests library decodes it into native Python dictionaries and lists with .json():

import requests

# URL parameters can be passed cleanly as a dictionary
params = {
    "page": 1,
    "limit": 5,
    "sort": "desc"
}

response = requests.get(
    "https://jsonplaceholder.typicode.com/posts",
    params=params,
    timeout=5  # Time out after 5 seconds if server hangs
)

print(f"Status Code: {response.status_code}")
print(f"Content Type: {response.headers.get('Content-Type')}")

if response.status_code == 200:
    posts = response.json()
    first_post = posts[0]
    print(f"First post title: {first_post['title']}")

Output:

Status Code: 200
Content Type: application/json; charset=utf-8
First post title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Sending Data with POST

When creating a new record, pass a Python dictionary to the json= parameter. requests will automatically serialize the dictionary into a JSON string and set the Content-Type: application/json header for you:

import requests

new_user = {
    "name": "Grace Hopper",
    "email": "grace@example.com",
    "role": "Lead Engineer"
}

response = requests.post(
    "https://jsonplaceholder.typicode.com/users",
    json=new_user,
    timeout=5
)

if response.status_code == 201:
    created_record = response.json()
    print("User successfully created with ID:", created_record["id"])

Production Error Handling: raise_for_status()

Never assume an API call will succeed. Servers go down, Wi-Fi drops, and rate limits get exceeded.

Instead of writing manual if response.status_code == 200: checks everywhere, call response.raise_for_status(). It does nothing on 2xx codes, but automatically raises a requests.exceptions.HTTPError on 4xx or 5xx:

import requests

def fetch_weather(city: str) -> dict:
    url = f"https://api.example.com/weather/{city}"
    
    try:
        response = requests.get(url, timeout=5)
        # Raises HTTPError if status is 404, 500, etc.
        response.raise_for_status()
        return response.json()
    except requests.exceptions.Timeout:
        print("Network timed out! The weather service is too slow.")
        return {}
    except requests.exceptions.ConnectionError:
        print("Failed to connect! Check your internet connection.")
        return {}
    except requests.exceptions.HTTPError as error:
        print(f"HTTP Error occurred ({response.status_code}): {error}")
        return {}
    except requests.exceptions.RequestException as error:
        print(f"Unexpected network error: {error}")
        return {}

Reusing Connections with requests.Session

If you are making multiple requests to the same domain (e.g. fetching 50 user profiles), calling requests.get() 50 times establishes and tears down 50 separate TCP/TLS handshakes, adding seconds of latency.

Using a Session keeps the underlying TCP connection alive, reuses authentication headers, and preserves cookies across calls:

import requests

session = requests.Session()
# Set headers once; they apply to every request made by this session
session.headers.update({
    "Authorization": "Bearer my_secret_token",
    "User-Agent": "MyPythonApp/1.0"
})

# Both requests reuse the exact same persistent TCP connection
profile = session.get("https://api.example.com/me", timeout=5).json()
settings = session.get("https://api.example.com/settings", timeout=5).json()

session.close()

Modern Async HTTP with httpx

When your application needs to fetch data from dozens of APIs concurrently without waiting for each one sequentially, use httpx with Python’s asyncio:

import asyncio
import httpx

async def fetch_item(client: httpx.AsyncClient, item_id: int):
    url = f"https://jsonplaceholder.typicode.com/todos/{item_id}"
    response = await client.get(url, timeout=5.0)
    return response.json()

async def main():
    async with httpx.AsyncClient() as client:
        # Fetch items 1, 2, and 3 concurrently in parallel!
        tasks = [fetch_item(client, i) for i in range(1, 4)]
        results = await asyncio.gather(*tasks)
        for item in results:
            print(f"Item #{item['id']}: {item['title']}")

asyncio.run(main())

Common Traps to Avoid

  1. Omitting timeout=: If an external API server is unresponsive, Python’s default behavior is to wait indefinitely. Your program or background worker will freeze forever. Always specify timeout=5 (or a tuple (connect_timeout, read_timeout)).
  2. Hardcoding API Keys: Never write secrets like API_KEY = "sk_live_12345" into your Python scripts. If you push the file to GitHub, scrapers will steal your credentials within seconds. Load them from environment variables instead (os.getenv("API_KEY")).
  3. Sequential looping instead of Sessions or Async: Calling requests.get() in a loop of 100 items will make your script painfully slow. Use requests.Session() or httpx.AsyncClient() with asyncio.gather().

Now that your code can store data safely and communicate across the internet with external APIs, you are ready to master high-performance Python—optimizing bottlenecks, memory footprint, and profiling in memory-performance.

Test your understanding of HTTP and REST APIs

Quick interactive practice questions with instant feedback.

Take Quiz →