Backend6 min read

Flask

Build lightweight Python web apps and REST APIs with Flask - blueprints, SQLAlchemy, authentication, and production deployment with Gunicorn.

FlaskPythonWeb FrameworkRESTMicroservices

skill: Flask category: Backend tags: [Flask, Python, Web Framework, REST, Microservices] readingTime: 6

Flask's minimalism is its strength - you choose every component. This flexibility makes it ideal for microservices and APIs where Django's full stack would be overkill. Use Flask's application factory pattern from the start to support testing and multiple environments.

Workflow

  1. Use the application factory patternCreating the Flask app in a factory function (not at module level) enables testing, multiple configs, and circular import prevention.
  2. Organize routes with blueprintsBlueprints split a Flask app into modular components - each feature has its own routes, templates, and static files.
  3. Add JWT authenticationStateless JWT authentication works well for REST APIs consumed by mobile apps or SPAs - no server-side session storage needed.
  4. Handle errors consistentlyUnhandled exceptions return HTML 500 error pages to API clients. Register error handlers to return JSON for all errors.
  5. Test Flask appsFlask's test client makes HTTP-level integration tests fast - no running server needed.

Output Format

Flask app: factory pattern, blueprints, JWT auth, JSON error handlers, and pytest integration tests.

create_app(config) → Flask
  db, migrate, jwt extensions
  blueprint registration (/api/v1)
Blueprint: routes per feature domain
Gunicorn: gunicorn -w 4 -b 0.0.0.0:8000 wsgi:app

Examples

Input

Output

Edge Cases & Gotchas

  • Application context outside request - Accessing db.session or current_app outside of a request/app context raises RuntimeError. Use with app.app_context(): for background tasks.
  • Thread-local request context - Flask's request and g objects are thread-local. In async contexts (gevent, asyncio), use the async Flask APIs or switch to FastAPI.
  • Development server in production - Never use flask run in production - it's single-threaded and has no worker management. Use Gunicorn: gunicorn -w 4 wsgi:app.
  • Before-request side effects - @app.before_request runs before every request including /health checks. Keep it lightweight - no DB calls that slow health checks.

When to Break These Rules

  • Use FastAPI instead of Flask for new greenfield APIs - FastAPI has built-in OpenAPI docs, async, and Pydantic validation.
  • Use Django if the app needs admin UI, ORM migrations, and auth out of the box - Flask requires assembling these separately.

Reference Files

  • https://flask.palletsprojects.com/
  • https://flask-jwt-extended.readthedocs.io/

More skills in this library

Browse all technical skills - Mobile, AI/ML, Web, Backend, Design, and Product.