Building RESTful APIs in Python – Endpoints, Routing, and JSON Responses
Quick Answer: A RESTful API connects web frontends to backend data using HTTP methods like GET and POST, clean route paths, and structured JSON responses.
Imagine Priya runs a busy South Indian cafe in Bengaluru receiving 1,000 food orders daily from mobile apps and browser screens.
The kitchen screen needs to fetch active orders, update statuses, and filter items by category without crashing or lagging.
How would you design robust API endpoints in Python to handle these requests reliably?
1. Why Do We Need Structured RESTful APIs?
The problem without standard APIs
We could write basic file scripts or unstructured server handlers that accept random text strings and return messy data.
Example 1: Unstructured HTTP server response without REST standards
This approach works for a single client, but it lacks standard routing and response formatting.
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHandler (BaseHTTPRequestHandler):
def do_GET (self ):
self .send_response (200 )
self .send_header ("Content-type", "text/plain")
self .end_headers ()
self .wfile.write (b "Id: 1, Item: Dosa, Price: 60")
def run ():
server = frozen = HTTPServer (("localhost", 8000 ), SimpleHandler)
server.serve_forever ()
Expected output
Id: 1, Item: Dosa, Price: 60
This code runs, but it has major scalability issues.
- Plain text strings cannot be parsed cleanly by modern JavaScript frontend apps.
- There is no automatic query parameter parsing for filtering items.
- Manual URL path matching gets extremely messy as the app grows.
We need a robust web framework to handle routing and JSON formatting automatically.
The solution: FastAPI and RESTful endpoints
API Endpoint = a specific URL path that accepts client requests and returns data.
Routing = mapping incoming URL paths to specific Python functions.
JSON response = structured text data formatted in JavaScript Object Notation for frontend consumption.
Figure 1: Incoming requests are matched by routes, processed, and returned as clean JSON.
2. Implement Routing and Parameter Parsing in FastAPI
Let us write a complete runnable Python API using FastAPI to manage menu items for Priya's cafe.
Example 2: FastAPI application with path and query parameters
This code sets up endpoints with parameter validation and structured JSON returns.
from fastapi import FastAPI, HTTPException
from typing import Optional
app = FastAPI ()
menu_database = [
{"id": 1 , "name": "Benne Dosa", "category": "Tiffin", "price": 60.0 },
{"id": 2 , "name": "Tatte Idli", "category": "Tiffin", "price": 40.0 },
{"id": 3 , "name": "Filter Coffee", "category": "Beverage", "price": 20.0 }
]
@app.get ("/menu")
def get_menu (category: Optional[str ] = None ):
if category:
return [item for item in menu_database if item["category"].lower () == category.lowerreturn menu_database
@app.get ("/menu/{item_id}")
def get_menu_item (item_id: int ):
for item in menu_database:
if item["id"] == item_id:
return item
raise HTTPException (status_code=404 , detail="Item not found")
Expected output (when requesting /menu/1)
{
"id": 1,
"name": "Benne Dosa",
"category": "Tiffin",
"price": 60.0
}
Notice how FastAPI automatically converts Python dictionaries into properly structured JSON responses.
Path parameters like {item_id} capture specific resource IDs from the URL.
| Raw http.server | FastAPI REST Endpoint |
|---|---|
| Manual string parsing required | Automatic JSON serialization |
| Complex if-else URL routing | Clean decorator routing @app.get() |
| Manual error status code setting | Built-in HTTPException handling |
The important terms to remember
- Endpoint = a specific URL route that accepts requests.
- Path Parameter = a variable embedded directly in the URL path.
- Query Parameter = optional key-value filters appended after the question mark in a URL.
- JSON = standard lightweight format for transmitting data between server and client.
Design tip: Always use plural nouns for collection endpoints, such as /menu or /orders.
3. Common Mistakes to Avoid
1. Confusing path parameters with query parameters
Putting required resource identifiers into query parameters instead of path parameters breaks RESTful design conventions.
Better approach: Use path parameters for identifying specific resources (like /menu/1) and query parameters for filtering or pagination (like /menu?category=Tiffin).
4. Interview Questions & Answers
Question 1: What is the difference between a path parameter and a query parameter?
What the interviewer expects: A clear distinction regarding resource identification versus optional filtering.
Strong answer: "A path parameter is required and identifies a specific resource, such as item ID 1 in /menu/1. A query parameter is optional and used for filtering or sorting, such as filtering the menu by ?category=Tiffin."
What interviewers expect at different levels
- Junior developer: Knows how to define route decorators and extract parameters in FastAPI.
- Senior developer: Understands HTTP status codes, payload validation, and API versioning.
- Technical architect: Designs stateless API architectures with robust error handling and serialization layers.
5. Practice Exercises
Beginner: Add an order endpoint
Create a POST endpoint /orders that accepts customer order data and returns a confirmation JSON object.
Expected result: Successful HTTP 201 response with order details.
Intermediate: Price filter query
Add a maximum price query parameter to the /menu endpoint to filter items below a certain amount.
Hint: Use optional float type annotations in your endpoint function arguments.
6. Frequently Asked Questions (FAQ)
Why do we use FastAPI over basic Python HTTP servers?
FastAPI provides automatic routing, data validation, interactive documentation, and fast async performance out of the box.
How does FastAPI generate interactive documentation?
FastAPI automatically generates Swagger UI docs at /docs based on standard Python type hints.
7. Next Steps
Now that you know how to build RESTful endpoints and parse parameters, you are ready to explore data validation and serialization with Pydantic in the next article.