๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 19 of 40
Lesson 19 of 40 Networking Intermediate โฑ 35 min

HTTP Requests & REST API Clients

Consume REST APIs with httpx and requests โ€” sessions, auth headers, retries, async HTTP, and writing typed API client wrappers.

Part 1: What You Will Learn

  • Send GET requests and inspect status codes.
  • Work with JSON responses.
  • Reuse connections with an HTTP client/session.
  • Add timeouts, headers, error handling, and an async client wrapper.

Part 2: Key Concepts

A REST client sends HTTP requests to an API endpoint and converts the response into Python data. Production code should always set sensible timeouts, check error responses, and isolate HTTP details inside a small client class rather than scattering requests throughout the application.

Part 3: Topic-Specific Code Examples

# Install once: pip install httpx
from typing import Any
import httpx

class JsonPlaceholderClient:
    def __init__(self) -> None:
        self.client = httpx.Client(
            base_url="https://jsonplaceholder.typicode.com",
            timeout=5.0,
            headers={"Accept": "application/json"},
        )

    def get_user(self, user_id: int) -> dict[str, Any]:
        response = self.client.get(f"/users/{user_id}")
        response.raise_for_status()
        return response.json()

    def close(self) -> None:
        self.client.close()

client = JsonPlaceholderClient()
try:
    user = client.get_user(1)
    print(user["name"], user["email"])
except httpx.HTTPError as exc:
    print("Request failed:", exc)
finally:
    client.close()
import asyncio
import httpx

async def load_posts() -> list[dict]:
    async with httpx.AsyncClient(
        base_url="https://jsonplaceholder.typicode.com",
        timeout=5.0,
    ) as client:
        response = await client.get("/posts", params={"userId": 1})
        response.raise_for_status()
        return response.json()

async def main() -> None:
    posts = await load_posts()
    print(f"Received {len(posts)} posts")

asyncio.run(main())

Part 4: How the Example Works

The client sets a base URL, default headers, and timeout once, then reuses the connection pool. raise_for_status() converts non-success HTTP responses into exceptions. The async version uses AsyncClient and is appropriate when many independent HTTP operations must run concurrently. These examples require an internet connection.

Part 5: Hands-On Practice

Mini project โ€” Typed API Browser. Add methods to list posts and retrieve one post. Validate the returned dictionary keys before displaying them, then add an async function that loads several post IDs concurrently with asyncio.gather().

Part 6: Next Steps

Run and modify the examples in Visual Studio 2026, then continue to Lesson 20. Return to Python Tutorial Home to review the complete curriculum.

๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’