How to expose a read-only Data API with FastAPI: step by step
This tutorial shows how to expose a read-only Data API using FastAPI to serve queries to a SQLite database. It is useful for sharing data securely and efficiently, with pagination and basic protection against misuse.
Prerequisites
- Python 3.10+ installed
- Basic knowledge of Python and SQL
- Packs: fastapi, uvicorn, sqlalchemy, pydantic (pip install fastapi uvicorn sqlalchemy pydantic)
Step 1: Minimal structure and why read-only
A read-only API prevents accidental data changes and simplifies authentication/control. Let's create the minimal structure with FastAPI and SQLAlchemy to query an "items" table.
project/
app.py
models.py
database.db # SQLite de exemplo
Step 2: Define the SQLAlchemy model and create sample data
We create a simple model for the items table with id, name and price. We use SQLite for portability.
# models.py
from sqlalchemy import Column, Integer, String, Float, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
price = Column(Float, nullable=False)
# Criar DB e adicionar dados de exemplo (executar uma vez)
if __name__ == '__main__':
engine = create_engine('sqlite:///database.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
s = Session()
s.add_all([
Item(name='Caneta', price=1.2),
Item(name='Caderno', price=3.5),
Item(name='Mochila', price=25.0)
])
s.commit()
s.close()
Step 3: Create the read-only API with FastAPI
We will expose two endpoints: list items with pagination and get an item by id. We use Pydantic for the response schema and ensure there are no routes that modify data.
# app.py
from fastapi import FastAPI, Depends, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Item, Base
DATABASE_URL = 'sqlite:///database.db'
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(bind=engine)
app = FastAPI(title='Items API Read-Only')
class ItemOut(BaseModel):
id: int
name: str
price: float
class Config:
orm_mode = True
# Dependência para obter sessão
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get('/items', response_model=list[ItemOut])
def list_items(page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), db=Depends(get_db)):
offset = (page - 1) * page_size
items = db.query(Item).offset(offset).limit(page_size).all()
return items
@app.get('/items/{item_id}', response_model=ItemOut)
def get_item(item_id: int, db=Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail='Item não encontrado')
return item
Step 4: Add simple authentication (API Key) and why
Even in read-only mode, it's wise to control who accesses the API. We will use an X-API-Key header and validate it with a dependency. In production, use an identity system.
from fastapi import Header
API_KEY = 'minha_chave_exemplo' # em produção não hardcode!
def verify_api_key(x_api_key: str = Header(...)):
if x_api_key != API_KEY:
raise HTTPException(status_code=401, detail='API Key inválida')
# aplicar verify_api_key como dependency global (exemplo)
app.dependencies.append(Depends(verify_api_key))
Step 5: Handle common errors and best practices
Common errors: forgetting connect_args on SQLite; not closing sessions; exposing write routes by mistake. It is recommended to limit page_size, validate parameters and log accesses for auditing.
# Exemplo simples de logging de consulta
import logging
logging.basicConfig(level=logging.INFO)
@app.middleware('http')
async def log_requests(request, call_next):
logging.info(f'Pedido {request.method} {request.url}')
response = await call_next(request)
return response
Verify the result
Run the API with uvicorn and test with curl or a browser. You should get paginated lists and details by id, and receive 401 without an API Key.
# Executar
uvicorn app:app --reload --port 8000
# Testes
curl -H "X-API-Key: minha_chave_exemplo" "http://localhost:8000/items?page=1&page_size=2"
curl -H "X-API-Key: minha_chave_exemplo" "http://localhost:8000/items/1"
Conclusion
You have just created a read-only Data API with FastAPI, SQLite and API Key authentication, with basic pagination and logging. Next steps: replace SQLite with a managed database, add automated tests and use OAuth2 or JWT for authentication. Tip: which metrics will you record to monitor API usage?