DEV Community

Sajjad Rahman
Sajjad Rahman

Posted 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)
Enter fullscreen mode Exit fullscreen mode

⚠️ 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
Enter fullscreen mode Exit fullscreen mode

βœ… 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)