Python Docs

REST API using Python

REST (Representational State Transfer) is a widely used architectural style for building HTTP APIs. In Python, you can build production-ready RESTful APIs using modern frameworks like FastAPI or Django REST Framework (DRF), while following standard conventions and best practices.

REST Principles

A good REST API follows consistent patterns for URLs, methods, and status codes.

  • Resources: Use nouns for endpoints, e.g. /users, /orders — not /getUsers.
  • HTTP Methods:
    • GET — read data
    • POST — create data
    • PUT/PATCH — update data
    • DELETE — delete data
  • Status Codes:
    • 200 OK — success
    • 201 Created — resource created
    • 400 Bad Request — invalid input
    • 404 Not Found — resource missing
    • 500 Internal Server Error — server failure
  • Stateless: Each request contains all needed information. Server does not keep client session between requests.

FastAPI (Modern & Fast)

FastAPI is a modern framework for building REST APIs with Python type hints. It automatically generates OpenAPI documentation and performs validation using Pydantic models.

Install FastAPI & Uvicorn

pip install fastapi uvicorn

Example: Basic REST API with FastAPI

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

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

items = [Item(id=1, name='Book', price=9.99)]

@app.get('/api/items')
def list_items():
    return items

@app.get('/api/items/{item_id}')
def get_item(item_id: int):
    item = next((i for i in items if i.id == item_id), None)
    if not item:
        raise HTTPException(status_code=404, detail='Not found')
    return item

@app.post('/api/items', status_code=201)
def create_item(item: Item):
    items.append(item)
    return item

# Run: uvicorn main:app --reload
# Docs: http://localhost:8000/docs

Highlights in this example:

  • Item is a Pydantic model — it validates incoming JSON and generates schema.
  • GET /api/items returns a list of items.
  • GET /api/items/{item_id} fetches a single item or returns 404.
  • POST /api/items creates a new item and returns it with status 201 Created.
  • FastAPI automatically exposes interactive docs at /docs (Swagger UI).

Django REST Framework (DRF)

Django REST Framework is a powerful toolkit for building Web APIs on top of Django. It provides serializers, viewsets, routers, authentication, and browsable API pages.

Install DRF

pip install djangorestframework

Example: Simple API with DRF

# serializers.py
from rest_framework import serializers

class ItemSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    price = serializers.FloatField()
# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def list_items(request):
    items = [{'id': 1, 'name': 'Book', 'price': 9.99}]
    return Response(items)

What DRF gives you:

  • Serializer classes to validate and serialize/deserialize data.
  • @api_view decorator to turn Django views into API endpoints.
  • Response object that handles content negotiation (JSON, etc.).
  • Easy integration with Django’s auth, permissions, and ORM.

Best Practices for REST APIs

  • Version your API: /api/v1/users, /api/v2/users etc.
  • Use pagination: Do not return thousands of records at once.
  • Add authentication: JWT, OAuth2, API keys, or session-based auth.
  • Rate limit requests: Avoid abuse and DDoS.
  • Document your API: OpenAPI/Swagger or ReDoc.
  • Validate inputs: Never trust client-side data, always validate on server.
  • Log errors & performance: Use logging and monitoring tools.

Summary

Python offers powerful tools for building RESTful APIs. FastAPI excels at modern, type-hinted APIs with automatic docs, while Django REST Framework shines when you already use Django and need rich integration with its ORM and authentication. Whichever you choose, following REST principles and best practices will help you build clean, maintainable backends.