Introduction to Web Frameworks in Python – Comparing Flask and FastAPI to Build Web Servers
Quick Answer: A web framework provides a pre-built structure for handling HTTP requests, routing URLs, and returning responses. Flask offers a lightweight, flexible approach, while FastAPI delivers high performance with automatic data validation.
Imagine Priya runs an online grocery delivery service in Bengaluru processing 5,000 customer orders every single day.
Each customer order arrives over the web as HTTP requests that need fast validation, routing, and JSON responses.
How would you build a robust backend server without writing complex networking code from scratch?
1. Why Do We Need Web Frameworks?
The problem without a framework
We could use Python's built-in http.server module to manually parse raw byte streams and check URL paths.
Example 1: Raw HTTP server without a framework
This script works, but manual string parsing for URLs and headers becomes tedious and error-prone.
from http.server import BaseHTTPRequestHandler, HTTPServer
class GroceryServer (BaseHTTPRequestHandler):
def do_GET (self ):
if self .path == "/orders":
self .send_response (200 )
self .send_header ("Content-type", "application/json")
self .end_headers ()
self .wfile.write (b'{"status": "active"}')
else :
self .send_error (404 )
if __name__ == "__main__":
server = HTTPServer (("localhost", 8000 ), GroceryServer)
server.serve_forever ()
Expected output
Server running on localhost:8000 (manual routing)
This code runs, but it has severe limitations for modern web applications.
- Manual string checking for every URL path gets messy quickly.
- Parsing incoming JSON request bodies requires writing custom parsing logic.
- There is no built-in data validation or automatic API documentation.
We need a web framework to manage routing and HTTP serialization automatically.
The solution: lightweight web frameworks
Framework = a pre-built software structure that handles the foundational plumbing for web applications.
Lightweight frameworks give you complete freedom over your project structure while handling core HTTP routing instantly.
Figure 1: Framework routers intercept incoming URLs and direct them to python handler functions.
2. Comparing Lightweight Frameworks: Flask vs FastAPI
Routing = matching incoming URL paths to specific Python functions.
Flask is a micro-framework created in 2010. It is simple, highly flexible, and ideal for quick prototypes and small applications.
FastAPI is a modern, high-performance framework built on standard Python type hints. It runs asynchronous code and generates interactive API documentation automatically.
3. Setting Up a Web Server with Flask
Let us write a runnable Flask server to manage Priya's grocery orders.
Example 2: Foundational Flask web server
This script defines a simple route returning JSON data using Flask.
from flask import Flask, jsonify
app = Flask (__name__)
.route ("/api/orders", methods=["GET"])
def get_orders ():
orders = [
{"id": 1 , "item": "Rice", "qty": 5 },
{"id": 2 , "item": "Sugar", "qty": 2 }
]
return jsonify (orders)
if __name__ == "__main__":
app.run (debug=True , port=5000 )
Expected output
* Running on http://127.0.0.1:5000
[
{"id": 1, "item": "Rice", "qty": 5},
{"id": 2, "item": "Sugar", "qty": 2}
]
Notice how @app.route cleanly connects the URL endpoint to our Python function.
4. Setting Up a Web Server with FastAPI
Now let us write the equivalent high-performance server using FastAPI.
Example 3: Foundational FastAPI web server
This script uses FastAPI with native type hints and automatic Swagger documentation.
from fastapi import FastAPI
app = FastAPI ()
.get ("/api/orders")
async def get_orders ():
return [
{"id": 1 , "item": "Rice", "qty": 5 },
{"id": 2 , "item": "Sugar", "qty": 2 }
]
Expected output
INFO: Uvicorn running on http://127.0.0.1:8000
[{"id": 1, "item": "Rice", "qty": 5}, {"id": 2, "item": "Sugar", "qty": 2}]
FastAPI automatically generates interactive Swagger documentation at /docs for testing your endpoints.
| Feature | Flask | FastAPI |
|---|---|---|
| Architecture | Synchronous micro-framework | Asynchronous modern framework |
| Type Hints | Optional / manual | Native validation via Pydantic |
| Documentation | Requires extensions (Flask-RESTful) | Built-in Swagger UI at /docs |
The important terms to remember
- Web Framework = a library providing structured routing and request handling.
- Routing = mapping URL paths to Python controller functions.
- Endpoint = a specific URL where clients access API services.
Design tip: Choose Flask for rapid prototyping with simple templates, and FastAPI for high-throughput APIs requiring strict data typing.
5. Common Mistakes to Avoid
1. Blocking the event loop in asynchronous frameworks
Running heavy blocking database queries or synchronous file operations inside an async def FastAPI route freezes the server.
Better approach: Use standard def for blocking operations or run tasks in thread pools.
6. Interview Questions & Answers
Question 1: What is the main difference between Flask and FastAPI?
What the interviewer expects: A clear distinction regarding concurrency models and native type validation.
Strong answer: "Flask is a synchronous micro-framework that gives developers total flexibility with extensions. FastAPI is built for high concurrency using Python async support and leverages Pydantic for automatic data validation and interactive documentation."
What interviewers expect at different levels
- Junior developer: Knows how to define basic routes and return JSON responses.
- Senior developer: Understands ASGI vs WSGI servers, event loops, and middleware configuration.
- Technical architect: Evaluates throughput, concurrency limits, and long-term maintainability.
7. Practice Exercises
Beginner: Static greeting endpoint
Create a Flask or FastAPI app with a root endpoint / that returns a welcome message for Priya's store.
Expected result: Visiting the root URL displays the welcome JSON response.
Intermediate: Query parameter filtering
Add a query parameter to your /api/orders route to filter items by minimum quantity.
Hint: Accept an optional integer parameter in your route function signature.
8. Frequently Asked Questions (FAQ)
Do I need an ASGI server for FastAPI?
Yes. FastAPI requires an ASGI server like Uvicorn or Hypercorn to run.
Can Flask run asynchronous code?
Yes, modern versions of Flask support async route definitions, though its ecosystem is primarily synchronous.
9. Next Steps
Now that you understand web frameworks and server setup, you are ready to build robust RESTful API endpoints and handle path parameters in the next article.