Python Docs

Building a Simple API

RESTful APIs allow clients (web, mobile, other services) to communicate with your backend over HTTP using JSON. Python makes it easy to build APIs quickly with frameworks like Flask and FastAPI.

REST API Basics

A simple user API usually supports operations like:

  • GET /api/users – list users
  • POST /api/users – create a user
  • GET /api/users/<id> – get a specific user (optional)
  • DELETE /api/users/<id> – delete a user (optional)

Let’s build the core list + create operations with Flask and FastAPI.

Flask API

Flask provides a simple way to define routes and return JSON responses using jsonify. We’ll build an in-memory user list API.

Install

pip install flask

Example: Simple Flask Users API

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

users = [{'id': 1, 'name': 'Alice'}]

@app.get('/api/users')
def get_users():
    return jsonify(users)

@app.post('/api/users')
def create_user():
    data = request.get_json()
    users.append(data)
    return jsonify(data), 201

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

What happens here:

  • users is an in-memory list storing user dictionaries.
  • GET /api/users returns all users as JSON.
  • POST /api/users reads JSON from the body and appends it to users.
  • Response code 201 indicates “Created”.

Note: In a real app, you’d generate IDs on the server and validate input instead of trusting the client.

FastAPI

FastAPI uses type hints and Pydantic models for automatic validation, documentation, and parsing. It’s great for scalable, production APIs.

Install

pip install fastapi uvicorn

Example: Simple FastAPI Users API

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str

users = [User(id=1, name='Alice')]

@app.get('/api/users')
def get_users():
    return users

@app.post('/api/users')
def create_user(user: User):
    users.append(user)
    return user

# Run: uvicorn main:app --reload

Key FastAPI features in this example:

  • User is a Pydantic model – FastAPI validates incoming JSON against id: int and name: str.
  • create_user(user: User) automatically receives a parsed User instance, not raw JSON.
  • Returning users or user gives JSON automatically.
  • You get auto docs at /docs and /redoc.

Flask vs FastAPI (for Simple APIs)

  • Flask: ultra-simple, good for small services or when you want full control.
  • FastAPI: better defaults for validation, typing, and documentation.
  • For professional APIs, you typically add:
    • Authentication (JWT, OAuth2)
    • Database integration (SQLAlchemy, ORM, etc.)
    • Error handling and logging
    • Pagination for large lists

Tips

  • Use proper HTTP status codes:200 OK, 201 Created, 400 Bad Request,404 Not Found, 500 Server Error
  • Always validate input data (types, required fields, ranges).
  • Handle errors gracefully and return helpful error JSON.
  • Do not store data only in memory for real apps — use a database.
  • Add tests to verify each endpoint’s behavior.