Web Framework
A web framework is a software framework designed to support the development of web applications, including web services, web resources, and web APIs. It provides a standard way to build and deploy web applications by offering libraries, tools, and modules that simplify common web development tasks. These tasks often include routing URLs to Python code, handling HTTP requests and responses, interacting with databases, managing sessions, and rendering HTML templates.
Web frameworks typically abstract away much of the complexity of network protocols (like HTTP) and provide a structured environment, allowing developers to focus more on the application's business logic rather than low-level implementation details. They can be full-stack (providing everything from ORMs to template engines) or micro-frameworks (providing only core functionalities and allowing developers to choose other components).
Starlette
Starlette is a lightweight ASGI (Asynchronous Server Gateway Interface) framework/toolkit for building high-performance asynchronous web services. It's designed for speed and simplicity, leveraging Python's `async`/`await` syntax to handle concurrent I/O operations efficiently, making it ideal for I/O-bound applications, real-time services, and microservices.
Key Features of Starlette:
1. ASGI Support: Built from the ground up to support ASGI, the modern asynchronous standard for Python web applications. This enables first-class `async`/`await` support throughout the framework.
2. High Performance: Due to its asynchronous nature and minimal overhead, Starlette is incredibly fast and efficient, capable of handling a large number of concurrent connections.
3. Robust Routing: Offers powerful routing capabilities, including URL matching, path parameters, query parameters, and regular expressions.
4. Middleware System: Provides a flexible middleware system to intercept and process requests and responses. This allows for functionalities like CORS, GZip compression, authentication, and logging to be easily added.
5. WebSockets: First-class support for WebSocket communication, enabling real-time, bidirectional communication between clients and the server.
6. Background Tasks: Allows you to run asynchronous tasks in the background after sending an HTTP response, which is useful for non-blocking operations like sending emails or processing data.
7. Testing Utilities: Includes an excellent `TestClient` for easily testing your asynchronous applications, supporting both synchronous and asynchronous test calls.
8. Extensibility: While lightweight, Starlette integrates seamlessly with other Python libraries. For instance, it works well with Pydantic for data validation and serialization (as seen in FastAPI, which is built on Starlette), Jinja2 for templating, and various ORMs.
9. Minimalist API: It provides just the essential tools for building web applications, giving developers more control and flexibility in choosing other components. This makes it a great choice for building custom APIs or when you need fine-grained control.
Starlette is often chosen when developers need the performance benefits of an ASGI framework without the extra opinions or features of larger frameworks. It's the underlying foundation for FastAPI, which adds automatic API documentation, data validation, and dependency injection on top of Starlette's core functionality.
In essence, combining 'Web Framework' with 'Starlette' means using Starlette as your chosen toolkit to build robust, high-performance, and scalable web applications or APIs in Python, leveraging its asynchronous capabilities and minimalist design.
Example Code
python
import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route, WebSocketRoute
Define asynchronous request handlers
async def homepage(request):
"""Handles requests to the root URL."""
return PlainTextResponse('Hello, Starlette!')
async def greet_user(request):
"""Handles requests to /greet/{name} with a path parameter."""
name = request.path_params['name']
return JSONResponse({"message": f"Greetings, {name}!"})
async def show_item(request):
"""Handles requests to /items/{item_id} with a path parameter and optional query parameter."""
item_id = request.path_params['item_id']
query_param = request.query_params.get('details', 'No details provided.')
return JSONResponse({
"item_id": item_id,
"description": f"This is item number {item_id}.",
"details_query": query_param
})
async def catch_all(request):
"""A route to catch all other unmatched paths."""
return PlainTextResponse(f"Path '{request.url.path}' not found.", status_code=404)
Define routes for the application
routes = [
Route('/', homepage),
Route('/greet/{name}', greet_user),
Route('/items/{item_id}', show_item),
Route('/{rest_of_path:path}', catch_all) Catch-all route
]
Create a Starlette application instance
app = Starlette(routes=routes)
To run this application:
1. Save the code as, for example, `main.py`.
2. Make sure you have uvicorn and starlette installed: `pip install uvicorn starlette`
3. Run from your terminal: `uvicorn main:app --reload`
Then open your browser or use curl:
- http://127.0.0.1:8000/
- http://127.0.0.1:8000/greet/Alice
- http://127.0.0.1:8000/items/123
- http://127.0.0.1:8000/items/456?details=some_additional_info
- http://127.0.0.1:8000/nonexistent/path
This block allows running the server directly from the script (optional, uvicorn CLI is preferred for production)
if __name__ == '__main__':
For development, you can run directly with uvicorn.run()
In a production environment, you would use a dedicated ASGI server process (e.g., 'uvicorn main:app')
uvicorn.run(app, host="0.0.0.0", port=8000)








Web Framework + Starlette