0
# Robyn
1
2
A Super Fast Async Python Web Framework with a Rust runtime. Robyn combines Python's ease of use with Rust's speed and safety, providing a simple, FastAPI-like API for building high-performance web applications and APIs with automatic OpenAPI generation, WebSocket support, middleware capabilities, and built-in features like hot reloading, dependency injection, and direct Rust integration.
3
4
## Package Information
5
6
- **Package Name**: robyn
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install robyn`
10
11
## Core Imports
12
13
```python { .api }
14
from robyn import Robyn, Request, Response
15
```
16
17
Common imports for building web applications:
18
19
```python { .api }
20
from robyn import (
21
Robyn, Request, Response, SubRouter,
22
serve_file, serve_html, html,
23
StreamingResponse, SSEResponse,
24
WebSocket, WebSocketConnector,
25
AuthenticationHandler, BearerGetter,
26
status_codes, jsonify, ALLOW_CORS
27
)
28
```
29
30
## Basic Usage
31
32
```python
33
from robyn import Robyn
34
35
# Create app instance
36
app = Robyn(__file__)
37
38
# Define a simple route
39
@app.get("/")
40
def index(request):
41
return "Hello, World!"
42
43
# Define a route with path parameters
44
@app.get("/user/<user_id>")
45
def get_user(request):
46
user_id = request.path_params["user_id"]
47
return f"User ID: {user_id}"
48
49
# Define a POST route with JSON handling
50
@app.post("/users")
51
def create_user(request):
52
user_data = request.json()
53
return {"message": "User created", "data": user_data}
54
55
# Start the server
56
if __name__ == "__main__":
57
app.start(host="0.0.0.0", port=8080)
58
```
59
60
## Architecture
61
62
Robyn's architecture combines Python's simplicity with Rust's performance:
63
64
- **Core Application**: The `Robyn` class serves as the main application instance, managing routing, middleware, and server lifecycle
65
- **Request/Response Pipeline**: Built on Rust runtime for high-performance HTTP handling with Python-friendly objects
66
- **Async Support**: Full async/await support with both sync and async route handlers
67
- **Middleware System**: Before/after request middleware with endpoint-specific or global scope
68
- **Router System**: Hierarchical routing with sub-routers for organizing large applications
69
- **WebSocket Integration**: Real-time communication with event-driven WebSocket handling
70
- **Authentication**: Pluggable authentication system with bearer token support
71
- **OpenAPI Generation**: Automatic API documentation generation with Swagger UI
72
73
## Capabilities
74
75
### Core Application
76
77
Main application class and routing functionality for creating web applications with HTTP methods, middleware, static file serving, and lifecycle management.
78
79
```python { .api }
80
class Robyn:
81
def __init__(
82
self,
83
file_object: str,
84
config: Config = Config(),
85
openapi_file_path: Optional[str] = None,
86
openapi: Optional[OpenAPI] = None,
87
dependencies: DependencyMap = DependencyMap()
88
): ...
89
90
def start(
91
self,
92
host: str = "127.0.0.1",
93
port: int = 8080,
94
_check_port: bool = True,
95
client_timeout: int = 30,
96
keep_alive_timeout: int = 20
97
): ...
98
99
def get(self, endpoint: str, auth_required: bool = False): ...
100
def post(self, endpoint: str, auth_required: bool = False): ...
101
def put(self, endpoint: str, auth_required: bool = False): ...
102
def delete(self, endpoint: str, auth_required: bool = False): ...
103
```
104
105
[Core Application](./core-app.md)
106
107
### Request and Response Handling
108
109
HTTP request and response objects with headers, query parameters, form data, file uploads, and response utilities including HTML, file serving, and streaming responses.
110
111
```python { .api }
112
@dataclass
113
class Request:
114
query_params: QueryParams
115
headers: Headers
116
path_params: dict[str, str]
117
body: Union[str, bytes]
118
method: str
119
url: Url
120
form_data: dict[str, str]
121
files: dict[str, bytes]
122
ip_addr: Optional[str]
123
identity: Optional[Identity]
124
125
def json(self) -> dict: ...
126
127
@dataclass
128
class Response:
129
status_code: int
130
headers: Union[Headers, dict]
131
description: Union[str, bytes]
132
response_type: Optional[str]
133
file_path: Optional[str]
134
135
def set_cookie(self, key: str, value: str): ...
136
```
137
138
[Request and Response](./request-response.md)
139
140
### WebSocket Support
141
142
Real-time communication with WebSocket connections, event handling (connect, message, close), broadcasting, and direct messaging capabilities.
143
144
```python { .api }
145
class WebSocket:
146
def __init__(
147
self,
148
robyn_object: "Robyn",
149
endpoint: str,
150
config: Config = Config(),
151
dependencies: DependencyMap = DependencyMap()
152
): ...
153
154
def on(self, type: str): ...
155
156
class WebSocketConnector:
157
id: str
158
query_params: QueryParams
159
160
def async_broadcast(self, message: str): ...
161
def async_send_to(self, sender_id: str, message: str): ...
162
def sync_broadcast(self, message: str): ...
163
def sync_send_to(self, sender_id: str, message: str): ...
164
```
165
166
[WebSocket](./websocket.md)
167
168
### Authentication
169
170
Pluggable authentication system with bearer token support, custom authentication handlers, and identity management for securing routes.
171
172
```python { .api }
173
class AuthenticationHandler:
174
def __init__(self, token_getter: TokenGetter): ...
175
def authenticate(self, request: Request) -> Optional[Identity]: ...
176
@property
177
def unauthorized_response(self) -> Response: ...
178
179
class BearerGetter:
180
def get_token(self, request: Request) -> Optional[str]: ...
181
def set_token(self, request: Request, token: str): ...
182
```
183
184
[Authentication](./authentication.md)
185
186
### OpenAPI Integration
187
188
Automatic API documentation generation with Swagger UI, route documentation, and custom OpenAPI specification support.
189
190
```python { .api }
191
class OpenAPI:
192
def add_openapi_path_obj(
193
self,
194
route_type,
195
endpoint,
196
openapi_name,
197
openapi_tags,
198
handler
199
): ...
200
def get_openapi_docs_page(self) -> str: ...
201
def get_openapi_config(self) -> dict: ...
202
def override_openapi(self, openapi_json_spec_path: str): ...
203
```
204
205
[OpenAPI](./openapi.md)
206
207
### Model Context Protocol (MCP) Integration
208
209
AI agent integration through MCP interface with resource registration, tool definitions, and prompt templates for building AI-enabled web applications.
210
211
```python { .api }
212
class MCPApp:
213
def resource(self, uri: str, name: str, description: str): ...
214
def tool(self, name: str, description: str, input_schema: dict): ...
215
def prompt(self, name: str, description: str): ...
216
```
217
218
[MCP Integration](./mcp.md)
219
220
### HTTP Status Codes
221
222
Comprehensive HTTP status code constants for proper response status handling, including informational, success, redirection, client error, and server error codes.
223
224
```python { .api }
225
# Standard HTTP status codes
226
HTTP_200_OK = 200
227
HTTP_201_CREATED = 201
228
HTTP_400_BAD_REQUEST = 400
229
HTTP_401_UNAUTHORIZED = 401
230
HTTP_404_NOT_FOUND = 404
231
HTTP_500_INTERNAL_SERVER_ERROR = 500
232
# ... and 67 more status code constants
233
```
234
235
[HTTP Status Codes](./status-codes.md)
236
237
### Template Rendering
238
239
Template rendering system with Jinja2 support and custom template interfaces for building dynamic web applications.
240
241
```python { .api }
242
class TemplateInterface(ABC):
243
@abstractmethod
244
def render_template(self, *args, **kwargs) -> Response: ...
245
246
class JinjaTemplate(TemplateInterface):
247
def __init__(self, directory: str, encoding: str = "utf-8", followlinks: bool = False): ...
248
def render_template(self, template_name: str, **kwargs) -> Response: ...
249
```
250
251
[Templating](./templating.md)
252
253
### Exception Handling
254
255
Exception classes for handling HTTP and WebSocket errors with proper status codes and error messages.
256
257
```python { .api }
258
class HTTPException(Exception):
259
def __init__(self, status_code: int, detail: str | None = None) -> None: ...
260
261
class WebSocketException(Exception):
262
def __init__(self, code: int, reason: str | None = None) -> None: ...
263
```
264
265
[Exception Handling](./exceptions.md)
266
267
## Types
268
269
```python { .api }
270
@dataclass
271
class Identity:
272
claims: dict[str, str]
273
274
@dataclass
275
class Url:
276
scheme: str
277
host: str
278
path: str
279
280
class Headers:
281
def __init__(self, default_headers: Optional[dict]): ...
282
def get(self, key: str): ...
283
def set(self, key: str, value: str): ...
284
def contains(self, key: str) -> bool: ...
285
286
class QueryParams:
287
def get(self, key: str, default: Optional[str] = None): ...
288
def get_all(self, key: str): ...
289
def set(self, key: str, value: str): ...
290
def to_dict(self) -> dict: ...
291
292
from enum import Enum
293
294
class HttpMethod(Enum):
295
GET = "GET"
296
POST = "POST"
297
PUT = "PUT"
298
DELETE = "DELETE"
299
PATCH = "PATCH"
300
OPTIONS = "OPTIONS"
301
HEAD = "HEAD"
302
TRACE = "TRACE"
303
CONNECT = "CONNECT"
304
305
class Events(Enum):
306
STARTUP = "startup"
307
SHUTDOWN = "shutdown"
308
```