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:
usersis an in-memory list storing user dictionaries.GET /api/usersreturns all users as JSON.POST /api/usersreads JSON from the body and appends it tousers.- Response code
201indicates “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 --reloadKey FastAPI features in this example:
Useris a Pydantic model – FastAPI validates incoming JSON againstid: intandname: str.create_user(user: User)automatically receives a parsedUserinstance, not raw JSON.- Returning
usersorusergives JSON automatically. - You get auto docs at
/docsand/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:
200OK,201Created,400Bad Request,404Not Found,500Server 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.