DEV Community

Sajjad Rahman
Sajjad Rahman

Posted on Edited on

Comparison between Flask and FastAPI for building APIs

🐍 Flask (WSGI-based Framework)

📦 Components:

  • Web Server: Gunicorn
  • Interface Protocol: WSGI (Web Server Gateway Interface)
  • API Code: Synchronous (Blocking I/O)

🔁 Flow:

  1. Client request hits the Gunicorn web server.
  2. Gunicorn forwards the request via WSGI (uses Werkzeug internally).
  3. The request reaches the Flask API code, where the endpoint is defined using @app.route(...).
  4. The function executes synchronously, blocking the thread until the task completes.
  5. Response is returned via jsonify(result).

📄 Code Example:

@app.route("/predict", methods=["POST"])
def predict():
    json_data = request.get_json()
    data = InputData(**json_data)
    result = predict_sync(data)
    return jsonify(result)
💬 Trending Now: sajjadrahman/comparison between flask and fastapi for building apis fg - Hot Topic 💬 Trending Now: sajjadrahman/comparison between flask and fastapi for building apis fg - Hot Topic

⚠️ Limitations:

  • Not suitable for async tasks (e.g., I/O-bound operations).
  • Can be less performant under high concurrency.

⚡ FastAPI (ASGI-based Framework)

📦 Components:

  • Web Server: Any ASGI server (e.g., Uvicorn)
  • Interface Protocol: ASGI (Asynchronous Server Gateway Interface)
  • API Code: Asynchronous (Non-blocking I/O)

🔁 Flow:

  1. Client request hits the ASGI-compatible web server.
  2. The request is passed through the ASGI interface.
  3. The FastAPI app handles it with @app.post(...).
  4. The function runs asynchronously, allowing concurrent processing.
  5. The response is returned directly.

📄 Code Example:

@app.post("/predict")
async def predict(data: InputData):
    result = await predict_async(data)
    return result
💬 Trending Now: sajjadrahman/comparison between flask and fastapi for building apis fg - Hot Topic 💬 Trending Now: sajjadrahman/comparison between flask and fastapi for building apis fg - Hot Topic

✅ Advantages:

  • Built-in support for async/await.
  • Higher performance for I/O-bound tasks.
  • Better suited for modern web applications and microservices.

🔄 Summary Table:

Feature Flask FastAPI
Protocol WSGI ASGI
Web Server Gunicorn Uvicorn/Hypercorn/etc.
Concurrency Model Synchronous (Blocking) Asynchronous (Non-blocking)
Async Support ❌ Not native ✅ Fully supported
Performance Medium High
Use Case Simple APIs, Synchronous High-concurrency, Async

Top comments (0)