A Super Fast Async Python Web Framework with a Rust runtime.
—
Main application functionality for creating Robyn web applications, including routing, middleware, static file serving, and server lifecycle management.
Create a Robyn application instance with optional configuration, OpenAPI integration, and dependency injection.
class Robyn:
def __init__(
self,
file_object: str,
config: Config = Config(),
openapi_file_path: Optional[str] = None,
openapi: Optional[OpenAPI] = None,
dependencies: DependencyMap = DependencyMap()
):
"""
Create a new Robyn application.
Args:
file_object: Usually __file__, used for relative path resolution
config: Application configuration options
openapi_file_path: Path to custom OpenAPI specification file
openapi: OpenAPI instance for documentation generation
dependencies: Dependency injection container
"""Start the server with configurable host, port, and timeout settings.
def start(
self,
host: str = "127.0.0.1",
port: int = 8080,
_check_port: bool = True,
client_timeout: int = 30,
keep_alive_timeout: int = 20
):
"""
Start the Robyn server.
Args:
host: Server host address
port: Server port number
_check_port: Whether to check if port is available
client_timeout: Client connection timeout in seconds
keep_alive_timeout: Keep-alive timeout in seconds
"""Define routes using HTTP method decorators with optional authentication and OpenAPI documentation.
def get(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""GET route decorator."""
def post(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""POST route decorator."""
def put(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""PUT route decorator."""
def delete(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""DELETE route decorator."""
def patch(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""PATCH route decorator."""
def head(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""HEAD route decorator."""
def options(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""OPTIONS route decorator."""
def connect(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""CONNECT route decorator."""
def trace(
self,
endpoint: str,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""TRACE route decorator."""Add routes programmatically with fine-grained control over route configuration.
def add_route(
self,
route_type,
endpoint: str,
handler,
is_const: bool = False,
auth_required: bool = False,
openapi_name: str = "",
openapi_tags: Optional[list] = None
):
"""
Add a route programmatically.
Args:
route_type: HTTP method type
endpoint: URL endpoint pattern
handler: Route handler function
is_const: Whether route response is constant
auth_required: Whether authentication is required
openapi_name: Name for OpenAPI documentation
openapi_tags: Tags for OpenAPI documentation
"""Add before-request and after-request middleware with global or endpoint-specific scope.
def before_request(self, endpoint: Optional[str] = None):
"""
Decorator for before-request middleware.
Args:
endpoint: Specific endpoint to apply middleware to, or None for global
"""
def after_request(self, endpoint: Optional[str] = None):
"""
Decorator for after-request middleware.
Args:
endpoint: Specific endpoint to apply middleware to, or None for global
"""Serve static files and directories with optional index files and directory listing.
def serve_directory(
self,
route: str,
directory_path: str,
index_file: Optional[str] = None,
show_files_listing: bool = False
):
"""
Serve static files from a directory.
Args:
route: URL route pattern
directory_path: Local directory path to serve
index_file: Default file to serve (e.g., "index.html")
show_files_listing: Whether to show directory listing
"""Handle application startup and shutdown events.
def startup_handler(self, handler):
"""
Register a startup event handler.
Args:
handler: Function to call on application startup
"""
def shutdown_handler(self, handler):
"""
Register a shutdown event handler.
Args:
handler: Function to call on application shutdown
"""Include sub-routers for organizing large applications with route prefixes.
def include_router(self, router):
"""
Include a sub-router in the application.
Args:
router: SubRouter instance to include
"""
class SubRouter:
def __init__(
self,
file_object: str,
prefix: str = "",
config: Config = Config(),
openapi: OpenAPI = OpenAPI()
):
"""
Create a sub-router with optional prefix.
Args:
file_object: Usually __file__
prefix: URL prefix for all routes in this router
config: Router configuration
openapi: OpenAPI instance for documentation
"""Configure application-wide authentication handling.
def configure_authentication(self, authentication_handler: AuthenticationHandler):
"""
Configure authentication for the application.
Args:
authentication_handler: Authentication handler instance
"""Set global exception handlers for unhandled errors.
def exception(self, exception_handler):
"""
Register a global exception handler.
Args:
exception_handler: Function to handle uncaught exceptions
"""Configure Cross-Origin Resource Sharing (CORS) for the application.
def ALLOW_CORS(
app: Robyn,
origins: Union[List[str], str],
headers: Union[List[str], str] = None
):
"""
Configure CORS for a Robyn application.
Args:
app: Robyn application instance
origins: Allowed origins (string or list of strings)
headers: Allowed headers (string or list of strings)
"""from robyn import Robyn
app = Robyn(__file__)
@app.get("/")
def home(request):
return "Welcome to Robyn!"
@app.get("/api/status")
def status(request):
return {"status": "healthy", "version": "1.0.0"}
if __name__ == "__main__":
app.start(host="0.0.0.0", port=8080)from robyn import Robyn
import time
app = Robyn(__file__)
@app.before_request()
def add_cors_headers(request):
print(f"Processing request to {request.url.path}")
@app.after_request()
def log_response(request, response):
print(f"Response status: {response.status_code}")
return response
@app.before_request("/api")
def api_middleware(request):
request.start_time = time.time()
@app.get("/api/data")
def get_data(request):
return {"message": "API data", "timestamp": time.time()}
app.start()from robyn import Robyn, SubRouter
app = Robyn(__file__)
# Create API router
api_router = SubRouter(__file__, prefix="/api/v1")
@api_router.get("/users")
def list_users(request):
return {"users": ["alice", "bob"]}
@api_router.post("/users")
def create_user(request):
user_data = request.json()
return {"message": "User created", "user": user_data}
# Include the router
app.include_router(api_router)
# Regular routes
@app.get("/")
def home(request):
return "Main application"
app.start()from robyn import Robyn
app = Robyn(__file__)
# Serve static files
app.serve_directory("/static", "./public", show_files_listing=True)
# Serve SPA with index.html fallback
app.serve_directory("/", "./dist", index_file="index.html")
@app.get("/api/info")
def api_info(request):
return {"api": "v1", "static": "available at /static"}
app.start()Install with Tessl CLI
npx tessl i tessl/pypi-robyn