Python Docs

Building APIs

Python is widely used for building web APIs. Two popular choices are: Flask, a minimal micro-framework, and FastAPI, a modern, type-hint–driven framework known for speed and automatic documentation.

What is an API?

An API (Application Programming Interface) lets clients (web apps, mobile apps, other services) talk to your backend. Typically, you:

  • Expose endpoints like GET /users, POST /login.
  • Receive JSON payloads, validate them, and perform logic.
  • Return structured JSON responses with status codes.

Flask API

Flask is great for small to medium APIs where you want full control over structure and components. You manually handle routing, parsing, and validation (or use extensions).

Install Flask

pip install flask

Example: Simple Flask API

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.get('/api/ping')
def ping():
    return jsonify({'pong': True})

@app.post('/api/echo')
def echo():
    data = request.get_json() or {}
    return jsonify({'you_sent': data})

if __name__ == '__main__':
    app.run()

What this API does:

  • GET /api/ping returns {'pong': True} to check if the API is alive (health/ping endpoint).
  • POST /api/echo reads JSON from the request body and returns it under you_sent.
  • request.get_json() parses JSON; or {} avoids None.

FastAPI

FastAPI is a modern, high-performance framework for building APIs with Python type hints. It automatically generates interactive API docs and performs data validation using Pydantic models.

Install FastAPI & Uvicorn

pip install fastapi uvicorn

Example: FastAPI with Pydantic

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get('/ping')
def ping():
    return {'pong': True}

@app.post('/items')
def create_item(item: Item):
    return item

# run: uvicorn app:app --reload

Key FastAPI features in this example:

  • Item is a Pydantic model with typed fields (str, float).
  • create_item automatically:
    • Parses JSON into an Item instance.
    • Validates types and required fields.
    • Returns JSON back to the client.
  • FastAPI auto-generates docs:
    • /docs (Swagger UI)
    • /redoc (ReDoc UI)
  • uvicorn app:app --reload runs the app with hot reload.

Flask vs FastAPI for APIs

  • Flask: Simple, flexible, great for small APIs or when you want full control.
  • FastAPI: Modern, type-hint–based, great for large APIs and teams who value validation & speed.

Notes & Best Practices

  • Always return proper HTTP status codes (e.g., 200, 201, 400, 404, 500).
  • Use structured error handlers (e.g., custom error responses for validation errors).
  • Add authentication (JWT, OAuth2, sessions) for protected endpoints.
  • Implement pagination for large lists (e.g., ?page=1&limit=20).
  • Add rate limiting to protect against abuse.
  • Write unit tests for endpoints using tools like pytest.