Class-based Endpoints
Relevant source files
The following files were used as context for generating this wiki page:
Class-based endpoints in Starlette provide a structured way to group logic for different HTTP methods or WebSocket events within a single class. This approach promotes code organization by allowing developers to define handlers as methods (e.g., get, post) instead of using conditional logic within a single function.
These endpoints are ASGI-compatible and integrate seamlessly with Starlette's routing system and schema generation tools. Sources: starlette/endpoints.py, starlette/routing.py:343-356
HTTPEndpoint
The HTTPEndpoint class allows for dispatching HTTP requests to methods named after the HTTP verbs. When a request is received, the endpoint identifies the method (GET, POST, etc.) and calls the corresponding lowercase method defined in the subclass.
Request Dispatching Logic
The dispatch method is responsible for routing the incoming request to the appropriate handler. If a HEAD request is received and no head method is defined, it defaults to the get method. If the requested method is not implemented or allowed, it returns a "405 Method Not Allowed" response. Sources: starlette/endpoints.py:27-44
The diagram above illustrates the decision-making process within the dispatch method to resolve which class method should handle the request. Sources: starlette/endpoints.py:27-44
Supported HTTP Methods
The endpoint automatically detects supported methods by checking for the existence of specific lowercase method names.
| Method | Handler Name | Note |
|---|---|---|
| GET | get(self, request) | Primary retrieval method. |
| POST | post(self, request) | Creation/Submission method. |
| PUT | put(self, request) | Update method. |
| PATCH | patch(self, request) | Partial update method. |
| DELETE | delete(self, request) | Removal method. |
| HEAD | head(self, request) | Defaults to get if missing. |
| OPTIONS | options(self, request) | Pre-flight/Capabilities check. |
Sources: starlette/endpoints.py:17-22, starlette/endpoints.py:29-30
WebSocketEndpoint
The WebSocketEndpoint class provides a stateful interface for handling WebSocket connections. It manages the connection lifecycle through specialized hook methods and provides built-in support for message decoding.
Connection Lifecycle
A WebSocketEndpoint follows a sequence of events: connection, optional message loop, and disconnection.
The sequence diagram shows how WebSocketEndpoint manages the flow from initial handshake to final closure. Sources: starlette/endpoints.py:65-83
Encoding and Decoding
Developers can specify an encoding attribute to automatically parse incoming messages.
text: Expects and returns string data.bytes: Expects and returns raw bytes.json: Automatically parses text or bytes into Python dictionaries/lists usingjson.loads.
If the received message type does not match the expected encoding, a RuntimeError is raised and the socket is closed with a 1003 UNSUPPORTED DATA code. Sources: starlette/endpoints.py:53, starlette/endpoints.py:85-111
Integration with Routing and Schemas
Class-based endpoints are treated as ASGI applications. When defined in a Route, Starlette detects if the endpoint is a class and handles instantiation during the request cycle. Sources: starlette/routing.py:353-356
Schema Generation
The SchemaGenerator inspects class-based endpoints to extract documentation from individual method docstrings. This allows for fine-grained API documentation where each HTTP verb has its own schema definition. Sources: starlette/schemas.py:73-78, tests/test_schemas.py:55-75
class OrganisationsEndpoint(HTTPEndpoint):
def get(self, request: Request) -> None:
"""
responses:
200:
description: A list of organisations.
"""
pass
Sources: tests/test_schemas.py:55-65
Route Representation
When a class-based endpoint is used in a route, its __name__ (or the class name) is used as the default route name for URL reversing. Sources: starlette/routing.py:118, tests/test_routing.py:669-672
Summary
Class-based endpoints simplify the implementation of complex resources by mapping HTTP verbs and WebSocket events to class methods. HTTPEndpoint provides a robust dispatch mechanism for RESTful services, while WebSocketEndpoint offers a structured lifecycle for real-time communication, including automated data decoding. These components ensure that Starlette remains modular and extensible for various architectural patterns. Sources: starlette/endpoints.py, starlette/routing.py