Nexios is a high-performance, Python-based web framework powered by Granian, a blazing-fast Rust-based ASGI server. Designed for speed, flexibility, and simplicity, Nexios delivers exceptional performance through its native Rust engine while maintaining the simplicity and elegance of Python. It supports RESTful APIs, authentication, and integrates easily with any ORM. Built for modern web development, Nexios allows developers to quickly spin up scalable, modular apps with minimal boilerplate—ideal for startups, rapid prototyping, and custom backend solutions. Think Django's capability with Rust-powered speed.
Avoid Hardcoding Secrets in Nexios; Use Environment Variables for Better Security!
To install Nexios, you can use several methods depending on your environment and preferred package manager. Below are the instructions for different package managers:
To install Nexios using pip
, the most common Python package manager, run the following command:
pip install nexios
Nexios includes a powerful CLI tool to help you bootstrap projects and run development servers.
nexios new my_project
Options:
--output-dir, -o
: Directory where the project should be created (default: current directory)--title
: Display title for the project (defaults to project name)
nexios run
Options:
--app, -a
: Application import path (default: main:app)--host
: Host to bind the server to (default: 127.0.0.1)--port, -p
: Port to bind the server to (default: 4000)--reload/--no-reload
: Enable/disable auto-reload (default: enabled)--log-level
: Log level for the server (default: info)--workers
: Number of worker processes (default: 1)--interface
: Server interface type: asgi, wsgi, or asgi-http (default: asgi)--http-protocol
: HTTP protocol: h11, h2, or auto (default: auto)--threading/--no-threading
: Enable/disable threading (default: disabled)--access-log/--no-access-log
: Enable/disable access logging (default: enabled)
If you're managing your project's dependencies with pipenv
, use the following command:
pipenv install nexios
If you're working with Conda environments, you can install Nexios from the Conda Forge channel:
conda install -c conda-forge nexios
For projects managed with poetry
, use this command to add Nexios to your dependencies:
poetry add nexios
If you want to install Nexios directly from its Git repository (for example, if you need the latest code or want to contribute), you can use this command:
pip install git+https://github.com/nexios-labs/nexios.git
Nexios leverages Granian, a high-performance Rust-based ASGI server, providing significant performance advantages:
- Rust-Powered Core: The underlying server is written in Rust, offering near-native performance while maintaining Python's flexibility
- Async by Default: Built for high-concurrency workloads using Python's async capabilities
- Optimized Resource Usage: Lower memory footprint and CPU utilization compared to pure Python servers
- HTTP/2 Support: Native support for modern HTTP protocols
- WebSocket Optimization: Efficient WebSocket handling for real-time applications
Benchmark comparisons show that Nexios with Granian can handle significantly more requests per second compared to traditional Python ASGI servers, with lower latency and better resource utilization.
- Routing
- Automatic OpenAPI Documentation
- Session Management
- File Router
- Authentication (Limited)
- Event Listener for Signals (Similar to Blinker)
- Middleware Support
- Express-like Functionality
- JWT Authentication
- Pydantic Support
- In-built Support for CORS
- Custom Decorators
- WebSocket Support
- Custom Error Handling
- Pagination
- Rust-Powered Granian Server Integration
- HTTP/2 Support
- High-Performance Async Processing
- Inbuilt Database ORM Integration
- Asynchronous Task Queue
- Rate Limiting
- API Throttling
from typing import List, Optional
from uuid import uuid4, UUID
from pydantic import BaseModel
from nexios import get_application
from nexios.exceptions import HTTPException
from nexios.http import Request, Response
from nexios.routing import Router
from pydantic import ValidationError
# Create the app
app = get_application()
async def handle_validation_error(request: Request, response: Response, err: ValidationError):
return response.json(err.errors(), status_code=400)
app.add_exception_handler(ValidationError, handle_validation_error)
# Create a router for our API with a prefix
api_router = Router(prefix="/api")
# Pydantic models for data validation
class TaskBase(BaseModel):
title: str
description: Optional[str] = None
class TaskCreate(TaskBase):
pass
class Task(TaskBase):
id: UUID
completed: bool = False
class Config:
orm_mode = True
# In-memory "database"
tasks_db: List[Task] = []
# Startup handler to initialize some sample data
@app.on_startup
async def initialize_sample_data():
global tasks_db
tasks_db = [
Task(
id=uuid4(),
title="Learn Nexios",
description="Study the Nexios framework documentation",
completed=False
),
Task(
id=uuid4(),
title="Build API",
description="Create a task manager API with Nexios",
completed=True
)
]
print("Sample data initialized")
# Routes
@api_router.get("/tasks", responses=List[Task], tags=["tasks"])
async def list_tasks(request: Request, response: Response):
"""List all tasks"""
return response.json(tasks_db)
@api_router.post("/tasks", responses=Task, tags=["tasks"], request_model=TaskCreate)
async def create_task(request: Request, response: Response):
"""Create a new task"""
request_body = await request.json
task_data = TaskCreate(**request_body)
new_task = Task(
id=uuid4(),
title=task_data.title,
description=task_data.description,
completed=False
)
tasks_db.append(new_task)
return response.json(new_task)
@api_router.get("/tasks/{task_id}", responses=Task, tags=["tasks"], request_model=TaskCreate)
async def get_task(request: Request, response: Response):
"""Get a specific task by ID"""
task_id = UUID(request.path_params["task_id"])
for task in tasks_db:
if task.id == task_id:
return response.json(task)
raise HTTPException(status_code=404, detail="Task not found")
@api_router.put("/tasks/{task_id}", responses=Task, tags=["tasks"], request_model=TaskCreate)
async def update_task(request: Request, response: Response):
"""Update a task"""
task_id = UUID(request.path_params["task_id"])
request_body = await request.json
task_update = TaskBase(**request_body)
for idx, task in enumerate(tasks_db):
if task.id == task_id:
updated_task = Task(
id=task_id,
title=task_update.title,
description=task_update.description,
completed=task.completed # Preserve completion status
)
tasks_db[idx] = updated_task
return response.json(updated_task)
raise HTTPException(status_code=404, detail="Task not found")
@api_router.patch("/tasks/{task_id}/complete", responses=Task, tags=["tasks"], request_model=TaskCreate)
async def complete_task(request: Request, response: Response):
"""Mark a task as completed"""
task_id = UUID(request.path_params["task_id"])
for idx, task in enumerate(tasks_db):
if task.id == task_id:
updated_task = Task(
id=task_id,
title=task.title,
description=task.description,
completed=True
)
tasks_db[idx] = updated_task
return response.json(updated_task)
raise HTTPException(status_code=404, detail="Task not found")
@api_router.delete("/tasks/{task_id}", tags=["tasks"])
async def delete_task(request: Request, response: Response):
"""Delete a task"""
global tasks_db
task_id = UUID(request.path_params["task_id"])
for idx, task in enumerate(tasks_db):
if task.id == task_id:
deleted_task = tasks_db.pop(idx)
return response.json({"message": f"Task {deleted_task.title} deleted"})
raise HTTPException(status_code=404, detail="Task not found")
# Mount the API router
app.mount_router(api_router)
# Add a simple root route
@app.get("/")
async def root(request: Request, response: Response):
return response.json({"message": "Task Manager API is running"})
# Shutdown handler
@app.on_shutdown
async def cleanup():
print("Shutting down task manager...")
if __name__ == "__main__":
# Nexios uses Granian by default, but you can also run it directly:
import granian
granian.run(app, host="0.0.0.0", port=4000, interface="asgi", access_log=True)
# Or simply use the Nexios CLI:
# nexios run
Visit http://localhost:4000/docs to view the Swagger API documentation.
"Adopting Nexios at our startup has been a practical and effective choice. In a fast-moving development environment, we needed something lightweight and efficient — Nexios met that need.
Its clean architecture and compatibility with different ORMs helped our team work more efficiently and keep things maintainable. One of its strengths is how straightforward it is — minimal overhead, just the tools we need to build and scale our backend services.
Credit to Dunamis for introducing Nexios to the team. It’s now a steady part of our stack, and it’s serving us well. — Joseph Mmadubuike , Chief Technology Officer buzzbuntu.com
👉 https://nexios-labs.gitbook.io/nexios
Sure thing, Dunamis! Here's a well-written "Donate" section for Nexios with more context, purpose, and a call to action. You can just replace the link with your actual Buy Me a Coffee profile:
Nexios is a passion project built to make backend development in Python faster, cleaner, and more developer-friendly. It’s fully open-source and maintained with love, late nights, and lots of coffee.
If Nexios has helped you build something awesome, saved you time, or inspired your next project, consider supporting its continued development. Your donation helps cover hosting, documentation tools, and fuels new features and updates.
Every little bit counts — whether it's the cost of a coffee or more. Thank you for believing in the project!
👉 Buy Me a Coffee and support the future of Nexios.