LightAPI is a fast, async-ready Python REST API framework that lets you instantly generate CRUD endpoints from SQLAlchemy models or your existing database schema. With built-in OpenAPI documentation, JWT authentication, Redis caching, and YAML-driven configuration, LightAPI is the best choice for building scalable, production-ready APIs in Python.
- Why LightAPI?
- Who is LightAPI for?
- Features: Python REST API, Async, CRUD, OpenAPI, JWT, Caching
- Feature Details & Usage
- Automatic CRUD Endpoints with SQLAlchemy
- YAML-Driven API Generation (Database Reflection)
- OpenAPI/Swagger Documentation
- Works with All Major Databases
- Environment-based Configuration
- JWT Authentication and Security
- CORS Support for Python APIs
- Custom Middleware for Python APIs
- Async/Await Support for High-Performance Python APIs
- Redis Caching for Python APIs
- Filtering, Pagination, and Sorting
- Request Validation
- Type Hints & Modern Python
- Comprehensive Error Handling
- Quick Start: Build a Python REST API in Minutes
- Example Endpoints
- Documentation
- FAQ
- Comparison
- License
- Troubleshooting
LightAPI is a modern, async-ready Python REST API framework designed for rapid development and production use. Instantly generate CRUD endpoints from your SQLAlchemy models or YAML config, with full support for OpenAPI docs, JWT authentication, Redis caching, request validation, and more. LightAPI is ideal for anyone who wants to build scalable, maintainable, and high-performance APIs in Python.
- Backend developers who want to ship APIs fast, with minimal code.
- Data engineers needing to expose existing databases as RESTful services.
- Prototypers and startups who want to iterate quickly and scale later.
- Anyone who wants a clean, maintainable, and extensible Python API stack.
LightAPI is designed to cover all the essentials for modern API development. Features are grouped for clarity:
- Automatic CRUD Endpoints with SQLAlchemy
- YAML-Driven API Generation (Database Reflection)
- OpenAPI/Swagger Documentation
- Works with All Major Databases
- Environment-based Configuration
- JWT Authentication and Security
- CORS Support for Python APIs
- Custom Middleware for Python APIs
- Async/Await Support for High-Performance Python APIs
- Redis Caching for Python APIs
- Filtering, Pagination, and Sorting
- Request Validation
- Type Hints & Modern Python
- Comprehensive Error Handling
Instantly generate RESTful endpoints for your models or tables, so you can create, read, update, and delete records with no manual wiring.
from lightapi import LightApi
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
app = LightApi()
app.register(User)
How to use: Define your SQLAlchemy model, register it with app.register()
, and LightAPI will expose full CRUD endpoints automatically.
Use cases: Quickly build admin panels, internal tools, or MVPs where you need instant API access to your data.
Point LightAPI at your existing database and expose tables as REST endpoints without writing model code. Learn more about SQLAlchemy.
# config.yaml
database_url: sqlite:///mydata.db
tables:
- name: users
crud: [get, post, put, patch, delete]
from lightapi import LightApi
api = LightApi.from_config('config.yaml')
api.run()
How to use: Create a YAML config describing your database and tables, then use LightApi.from_config()
to generate endpoints instantly.
Use cases: Expose legacy or third-party databases as REST APIs for integration, analytics, or migration.
Get interactive API docs and OpenAPI JSON automatically, always in sync with your endpoints. Learn more about OpenAPI.
app = LightApi(swagger_title="My API", swagger_version="1.0.0")
# Visit http://localhost:8000/docs
How to use: Set Swagger options when creating your app. Docs are auto-generated and always up to date. Use cases: Share your API with frontend teams, generate client SDKs, or provide public API documentation.
Use SQLite, PostgreSQL, MySQL, or any SQLAlchemy-supported backend. SQLAlchemy Docs
app = LightApi(database_url="postgresql://user:pass@localhost/db")
# or
app = LightApi(database_url="mysql://user:pass@localhost/db")
How to use: Set the database_url
parameter to match your database backend.
Use cases: Migrate between databases, support multiple environments, or connect to cloud-hosted DBs.
Configure your app for development, testing, or production using environment variables or YAML.
# config.yaml
database_url: sqlite:///dev.db
debug: true
api = LightApi.from_config('config.yaml')
How to use: Store your settings in a YAML file or environment variables, then load them with from_config()
or os.environ
.
Use cases: Seamlessly switch between dev, staging, and production setups, or deploy with Docker and CI/CD.
Secure your API with industry-standard JSON Web Tokens, including login endpoints and protected resources. Learn more about JWT
from lightapi.auth import JWTAuthentication
class UserEndpoint(RestEndpoint):
class Configuration:
authentication_class = JWTAuthentication
# Set secret
export LIGHTAPI_JWT_SECRET="supersecret"
How to use: Add authentication_class = JWTAuthentication
to your endpoint's Configuration. Set the secret key as an environment variable.
Use cases: Protect sensitive endpoints, implement login/logout, and control access for different user roles.
Easily enable Cross-Origin Resource Sharing for frontend/backend integration. Learn more about CORS
from lightapi.core import CORSMiddleware
app.add_middleware([CORSMiddleware])
How to use: Add CORSMiddleware
to your app's middleware list to allow cross-origin requests from browsers.
Use cases: Enable frontend apps (React, Vue, etc.) to call your API from a different domain during development or production.
Add logging, rate limiting, authentication, or any cross-cutting logic with a simple middleware interface.
from lightapi.core import Middleware
class LoggingMiddleware(Middleware):
def process(self, request, response=None):
print(f"{request.method} {request.url}")
return response
app.add_middleware([LoggingMiddleware])
How to use: Subclass Middleware
and implement the process
method. Add your middleware to the app.
Use cases: Add request logging, enforce rate limits, or inject custom headers for all responses.
Built on aiohttp for high concurrency and fast response times. All endpoints are async-ready; just use async def
in your handlers. Learn more about aiohttp
class MyEndpoint(RestEndpoint):
async def get(self, request):
return {"message": "Async ready!"}
How to use: Write your endpoint methods as async def
to take full advantage of Python's async capabilities.
Use cases: Handle thousands of concurrent API requests, real-time dashboards, or chat/messaging backends.
Speed up your API with automatic or custom caching of responses, including cache invalidation. Learn more about Redis
from lightapi.cache import RedisCache
class Product(RestEndpoint):
class Configuration:
caching_class = RedisCache
caching_method_names = ['GET']
How to use: Set caching_class = RedisCache
and specify which HTTP methods to cache. LightAPI will cache responses transparently.
Use cases: Reduce database load for expensive queries, speed up product catalogs, or cache public data.
Query your data efficiently with flexible filters, paginated results, and sort options.
from lightapi.filters import ParameterFilter
from lightapi.pagination import Paginator
class ProductFilter(ParameterFilter): ...
class ProductPaginator(Paginator): ...
class Product(RestEndpoint):
class Configuration:
filter_class = ProductFilter
pagination_class = ProductPaginator
How to use: Implement custom filter and paginator classes, then assign them in your endpoint's Configuration. Use cases: Build APIs for large datasets, searchable product listings, or analytics dashboards.
Validate incoming data with custom or automatic validators, returning clear error messages.
from lightapi.rest import Validator
class UserValidator(Validator):
def validate_name(self, value):
if not value:
raise ValueError('Name required')
return value
class User(RestEndpoint):
class Configuration:
validator_class = UserValidator
How to use: Create a Validator class and assign it in your endpoint's Configuration. Validation errors are returned as 400 responses. Use cases: Enforce business rules, prevent bad data, and provide user-friendly error messages in your API.
All code is type-annotated and follows modern Python best practices for maintainability and IDE support.
Detailed error messages and robust error handling are built in, making debugging and production support easier.
pip install lightapi
from lightapi import LightApi
from lightapi.database import Base
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String(50))
email = Column(String(100))
app = LightApi()
app.register(User)
if __name__ == "__main__":
app.run()
# config.yaml
database_url: sqlite:///mydata.db
tables:
- name: users
crud: [get, post, put, patch, delete]
- name: orders
crud: [get, post]
from lightapi import LightApi
api = LightApi.from_config('config.yaml')
api.run(host="0.0.0.0", port=8081)
GET /users/
- List usersPOST /users/
- Create userGET /users/{id}
- Get user by IDPUT /users/{id}
- Replace userPATCH /users/{id}
- Update userDELETE /users/{id}
- Delete userGET /orders/
- List ordersPOST /orders/
- Create orderGET /orders/{id}
- Get order by ID
Q: Can I use LightAPI with my existing database?
A: Yes! Use the YAML config to reflect your schema and instantly expose REST endpoints.
Q: What databases are supported?
A: Any database supported by SQLAlchemy (PostgreSQL, MySQL, SQLite, etc.).
Q: How do I secure my API?
A: Enable JWT authentication and CORS with a single line.
Q: Can I customize endpoints or add business logic?
A: Yes, you can extend or override any handler, add middleware, and use validators.
Q: Is this production-ready?
A: Yes. LightAPI is designed for both rapid prototyping and production deployment.
Feature | LightAPI | FastAPI | Flask | Django REST |
---|---|---|---|---|
Zero-boilerplate CRUD generation | ✅ | ❌ | ❌ | ❌ |
YAML-driven API/config | ✅ | ❌ | ❌ | ❌ |
Async/await support | ✅ | ✅ | ❌ | ❌ |
Automatic OpenAPI/Swagger docs | ✅ | ✅ | ❌ | ✅ |
JWT authentication (built-in) | ✅ | ❌ | ❌ | ✅ |
CORS support (built-in) | ✅ | ✅ | ❌ | ✅ |
Redis caching (built-in) | ✅ | ❌ | ❌ | ✅ |
Request validation (customizable) | ✅ | ✅ | ❌ | ✅ |
Filtering, pagination, sorting | ✅ | ✅ | ❌ | ✅ |
Database reflection | ✅ | ❌ | ❌ | ❌ |
Type hints & modern Python | ✅ | ✅ | ❌ | ✅ |
Custom middleware | ✅ | ✅ | ✅ | ✅ |
Environment-based configuration | ✅ | ✅ | ❌ | ✅ |
Production-ready out of the box | ✅ | ✅ | ❌ | ✅ |
MIT License. See LICENSE.
Note: Only GET, POST, PUT, PATCH, DELETE HTTP verbs are supported. Required fields must be NOT NULL in the schema. Constraint violations (NOT NULL, UNIQUE, FK) return 409.
To start your API, always useapi.run(host, port)
. Do not use external libraries orapp = api.app
to start the server directly.
LightAPI - The fastest way to build Python REST APIs from your database.
If you see this error when running example scripts:
Traceback (most recent call last):
File "examples/mega_example.py", line 22, in <module>
from lightapi.auth import JWTAuthentication
ModuleNotFoundError: No module named 'lightapi'
Solution:
- Make sure you run the script from the project root directory, not from inside the
examples/
folder. - Or, set the
PYTHONPATH
to include the project root:
PYTHONPATH=. python3 examples/mega_example.py
This ensures Python can find the lightapi
package in your local project.