REST APIs
Build JSON-returning REST-style APIs with Flask. Flask itself is light enough — blueprints for versioning are all you need, no extra framework required.
Basic Structure
When a view returns a dict/list, Flask serializes it to JSON automatically and sets Content-Type: application/json:
Request Body Validation
request.get_json() raises 415/400 when the request isn't JSON; pass silent=True to get None instead and handle it yourself. For production projects, use Pydantic or Marshmallow for structured validation:
Pagination
Establish query-parameter conventions and a uniform response shape:
Uniform Error Responses
Make errors under the API blueprint return JSON instead of HTML error pages:
Authentication
Common options:
- Session cookie: simplest for same-origin, integrated frontend/backend apps.
- Token (Bearer): clients send
Authorization: Bearer <token>; the server verifies it and stores the user ong.current_user. - JWT: use the
Flask-JWT-Extendedextension for refresh tokens and expiry management.
Cross-Origin Requests (CORS)
When the frontend is deployed on a different domain, enable CORS:
Versioning Advice
- URL-prefix versioning (
/api/v1/) is the most intuitive — one blueprint per version. - Bump the version only for breaking changes (removed fields, changed semantics); adding fields stays backward-compatible.