Skip to main content

A lightweight framework for building API endpoints using Python's native libraries.

Project description

LightAPI

PyPI version Python 3.8+ License: MIT

A lightweight, fast, and easy-to-use web API framework for Python with automatic REST endpoint generation, built-in authentication, caching, and more.

Features

  • 🚀 Zero-boilerplate REST APIs - Automatically generate CRUD operations from SQLAlchemy models
  • 🔐 Built-in Authentication - JWT authentication with automatic CORS handling
  • High Performance - Built on Starlette for async support and speed
  • 💾 Smart Caching - Redis-based caching with automatic invalidation
  • 📊 Request Validation - Automatic request validation and error handling
  • 🔍 Advanced Filtering - Query filtering, pagination, and sorting out of the box
  • 📖 Auto Documentation - Automatic OpenAPI/Swagger documentation generation
  • 🔧 Flexible Middleware - Easy middleware system for custom logic
  • 🗄️ Database Integration - Seamless SQLAlchemy integration with automatic table creation
  • ⚙️ Environment Configuration - Easy configuration management

Quick Start

Installation

pip install lightapi

Basic Usage

from lightapi import LightApi
from lightapi.database import Base
from sqlalchemy import Column, Integer, String

# Define your model
class User(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    email = Column(String(100))

# Create API instance
app = LightApi()

# Register your model - automatically creates CRUD endpoints
app.register(User)

# Run the server
if __name__ == "__main__":
    app.run()

That's it! You now have a fully functional REST API with:

  • GET /users - List all users with filtering and pagination
  • GET /users/{id} - Get user by ID
  • POST /users - Create new user
  • PUT /users/{id} - Update user
  • DELETE /users/{id} - Delete user
  • OPTIONS /users - CORS preflight support

Dynamic API from YAML Config (SQLAlchemy Reflection)

LightAPI can instantly generate a REST API from a YAML configuration file, reflecting your database schema at runtime using SQLAlchemy. This is ideal for exposing existing databases with zero model code.

How It Works

  • Reflects the schema of specified tables from your database (PostgreSQL, MySQL, SQLite, etc.)
  • Dynamically generates SQLAlchemy models and CRUD endpoints for each table
  • Configurable: You control which tables and which CRUD operations (GET, POST, PUT, PATCH, DELETE) are exposed
  • Composite primary keys, unique constraints, foreign keys, BLOBs, JSON, and more are supported
  • Advanced edge cases (triggers, generated columns, partial unique constraints, etc.) are handled

End-to-End Example

1. Create a YAML Config

database_url: sqlite:///mydata.db

tables:
  - name: users
    crud: [get, post, put, patch, delete]
  - name: orders
    crud: [get, post]

2. Create Your Database (SQLite example)

sqlite3 mydata.db "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE); CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, amount REAL NOT NULL, FOREIGN KEY(user_id) REFERENCES users(id));"

3. Start the API

from lightapi import LightApi
import aiohttp.web

api = LightApi.from_config('my_api_config.yaml')
app = api.app

aiohttp.web.run_app(app, port=8080)

4. Use the API (with curl)

# Create a user
curl -X POST http://localhost:8080/users/ -H 'Content-Type: application/json' -d '{"name": "Alice", "email": "alice@example.com"}'

# List users
curl http://localhost:8080/users/

# Create an order for Alice (id=1)
curl -X POST http://localhost:8080/orders/ -H 'Content-Type: application/json' -d '{"user_id": 1, "amount": 42.5}'

# List orders
curl http://localhost:8080/orders/

FAQ & Tips

  • Server-side defaults: Only server_default (e.g., server_default=text('...')) are available after reflection. Python-side defaults are not reflected.
  • Composite PKs: Supported transparently in routes and handlers.
  • Error handling: Unique, check, not null, and foreign key constraints are enforced. Violations return 409 Conflict with details.
  • Partial CRUD: You can expose only the operations you want per table.
  • Supported DBs: Any DB supported by SQLAlchemy reflection (PostgreSQL, MySQL, SQLite, etc.)

See the docs for more advanced examples and details.

Documentation

Visit our comprehensive documentation at: https://iklobato.github.io/lightapi/

Advanced Features

Authentication

from lightapi.auth import JWTAuthentication

# Add JWT authentication
auth = JWTAuthentication(secret_key="your-secret-key")
app.add_middleware(auth)

# Protected endpoints automatically require valid JWT tokens

Caching

from lightapi.cache import RedisCache

# Add Redis caching
cache = RedisCache(host="localhost", port=6379)
app.register(User, cache=cache, cache_ttl=300)  # 5 minutes TTL

Validation

from lightapi.rest import Validator

class UserValidator(Validator):
    def validate_post(self, data):
        if not data.get("email"):
            raise ValueError("Email is required")
        return data

app.register(User, validator=UserValidator())
  • All required fields must be defined as NOT NULL in your database schema for correct enforcement.
  • The API will return 409 Conflict if you attempt to create or update a record missing a NOT NULL field, or violating a UNIQUE or FOREIGN KEY constraint.

Middleware

from lightapi.core import Middleware

class LoggingMiddleware(Middleware):
    async def process(self, request, call_next):
        print(f"Request: {request.method} {request.url}")
        response = await call_next(request)
        print(f"Response: {response.status_code}")
        return response

app.add_middleware(LoggingMiddleware())

Why LightAPI?

  • Rapid Development: Get REST APIs running in minutes, not hours
  • Production Ready: Built-in security, caching, and error handling
  • Flexible: Customize every aspect while keeping defaults simple
  • Modern: Async support, type hints, and contemporary Python practices
  • Well Documented: Comprehensive docs with real-world examples

Examples

Check out the examples directory for complete applications:

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.


LightAPI - Making web APIs light and fast

Note: Only GET, POST, PUT, PATCH, DELETE HTTP verbs are supported. OPTIONS and HEAD are not available. Required fields must be NOT NULL in the schema. Constraint violations (NOT NULL, UNIQUE, FK) return 409.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lightapi-0.1.4.tar.gz (184.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lightapi-0.1.4-py3-none-any.whl (34.6 kB view details)

Uploaded Python 3

File details

Details for the file lightapi-0.1.4.tar.gz.

File metadata

  • Download URL: lightapi-0.1.4.tar.gz
  • Upload date:
  • Size: 184.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.12

File hashes

Hashes for lightapi-0.1.4.tar.gz
Algorithm Hash digest
SHA256 1cd75f862f06242fed5561e690a452e83bf2ba68d03f71214fe2507f5f91ed9e
MD5 c58aeeffd87171444c270e3a870f1119
BLAKE2b-256 63e946560d089009d4443eda26729dc74933f3b227ebdeb66399ff0e9ec75dac

See more details on using hashes here.

File details

Details for the file lightapi-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: lightapi-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 34.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.12

File hashes

Hashes for lightapi-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 eac0d87c3f41884d6462cae8e5430c0b17ae36d19bea41b20b27902edbb11766
MD5 7ad0b25cd839d5c2f6211177cf988608
BLAKE2b-256 b6ccd078d61afb1ec2dc72898b085a74f236eb8058173992d0fe765aad7e9016

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page