Skip to content

Module 16 · External Libraries and APIs — topic 9 of 12

APIs

What web APIs are: endpoints, resources and URLs, REST conventions, JSON payloads, authentication with keys and tokens, rate limits, and reading API documentation — with a working local API built in Python.

Beginner 10 min read·Lesson 243 of 306 in Python Programming

Learning objectives

  • Explain endpoints, resources and REST conventions
  • Read URLs and build query strings
  • Call a JSON API from Python

Definition

An API (Application Programming Interface) is a defined way for programs to communicate. A web API exposes endpoints — URLs that accept HTTP requests and return data, usually JSON — so other programs can read or change information.

Introduction

When a weather app shows today's forecast, it asks a weather service's API for data. Your Python programs can do the same — or offer their own API to others.

Why it matters

APIs connect software. Knowing how they work lets your programs use data and services from the whole internet.

Detailed explanation

An endpoint is a URL for a resource, such as /books (a collection) or /books/2 (one item). Base URLs often include a version: https://api.example.com/v1.

REST APIs map actions to HTTP methods: GET reads, POST creates, PUT/PATCH update, DELETE removes.

Query parameters filter or page results: /books?author=austen&page=2. Build them with urllib.parse.urlencode (or requests' params).

Responses are usually JSON with a status code describing the outcome (see HTTP requests).

Most real APIs require authentication: an API key or token sent in a header such as Authorization: Bearer <token>. Keep these secret.

APIs enforce rate limits — a maximum number of requests per minute — and reply 429 Too Many Requests when exceeded.

Documentation describes each endpoint's URL, method, parameters, response format and errors. Read it before writing code.

Python's standard library (http.server, urllib.request) is enough to build and call simple APIs; frameworks like FastAPI and Flask are used for real services.

Syntax

Python
from urllib.request import urlopen
import json
with urlopen("https://api.example.com/v1/books?author=austen", timeout=10) as resp:
books = json.load(resp)
  • Endpoints are URLs for resources.
  • Methods express actions.
  • Responses are usually JSON.

Code examples

Anatomy of an API URL

Python
from urllib.parse import parse_qs, urlparse
u = urlparse("https://api.example.com/v1/books?author=austen&page=2")
print(u.scheme, u.netloc, u.path)
print(parse_qs(u.query))
Output
https api.example.com /v1/books
{'author': ['austen'], 'page': ['2']}

Building query strings safely

Python
from urllib.parse import quote, urlencode
base = "https://api.example.com/v1/search"
print(base + "?" + urlencode({"q": "data science", "lang": "en", "page": 1}))
print(quote("Tamil Nadu/2026"))
Output
https://api.example.com/v1/search?q=data+science&lang=en&page=1
Tamil%20Nadu/2026

More examples

A tiny JSON API and a client

Python
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.request import urlopen
BOOKS = {"1": {"title": "Dune", "year": 1965}, "2": {"title": "Emma", "year": 1815}}
class BookAPI(BaseHTTPRequestHandler):
def do_GET(self):
parts = self.path.strip("/").split("/")
if parts == ["books"]:
status, data = 200, [{"id": k, **v} for k, v in BOOKS.items()]
elif len(parts) == 2 and parts[0] == "books" and parts[1] in BOOKS:
status, data = 200, {"id": parts[1], **BOOKS[parts[1]]}
else:
status, data = 404, {"error": "not found"}
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), BookAPI)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
with urlopen(base + "/books", timeout=5) as resp:
print(resp.status, resp.headers["Content-Type"])
books = json.load(resp)
print([b["title"] for b in books])
with urlopen(base + "/books/2", timeout=5) as resp:
print(json.load(resp))
server.shutdown()
Output
200 application/json
['Dune', 'Emma']
{'id': '2', 'title': 'Emma', 'year': 1815}

Step-by-step explanation

  • The handler maps two endpoints — the collection /books and one item /books/<id> — and returns 404 for anything else.
  • The server listens on 127.0.0.1 port 0, meaning 'any free port on this computer', in a background thread.
  • The client side is exactly what you'd write for a real API: open the URL, check the status and parse the JSON.

Expected output

Running “A tiny JSON API and a client” prints exactly:

TextOutput
200 application/json
['Dune', 'Emma']
{'id': '2', 'title': 'Emma', 'year': 1815}

Practical applications

  • Payment gateways, maps, weather and translation services.
  • Mobile apps talking to their own back-end APIs.

Best practices

  • Read the API documentation first.
  • Keep keys in environment variables.
  • Respect rate limits and cache results.

Common mistakes

Building query strings by hand

Avoid

url = base + "?q=" + user_text

Prefer

url = base + "?" + urlencode({"q": user_text})

Spaces, & and other characters must be encoded or the request breaks.

Important notes

  • OpenAPI (Swagger) documents describe APIs in a machine-readable format that tools can turn into clients.

Key takeaways

  • APIs expose endpoints returning JSON.
  • HTTP methods express actions on resources.
  • Authentication, rate limits and documentation matter.

Try it yourself

  1. 1
    Add a /books?year_before=1900 filter to the local API and query it.
  2. 2
    Find a free public API and write down its base URL, one endpoint and its authentication method.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.