Flask extension for automatically generating RESTful APIs from SQLAlchemy models
Project description
flask-api-sqlalchemy
A Flask extension that automatically generates RESTful APIs from SQLAlchemy models.
Features
- Simple integration with existing Flask and SQLAlchemy applications
- Automatic discovery of SQLAlchemy models
- Automatic mapping of SQLAlchemy types to Flask-RESTX API model types
- Fully generated REST endpoints for all models
- Comprehensive test suite
- Interactive Swagger UI documentation
- Command-line scaffolding tool for quick setup
Installation for Your Project
pip install flask-api-sqlalchemy
Installation for Development
pip install -e .
Quick Start
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_api_sqlalchemy import Api
# Create Flask application
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
# Initialize SQLAlchemy
db = SQLAlchemy(app)
# Define your SQLAlchemy models
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
# Initialize the API extension
api = Api()
api.init_app(app, db)
if __name__ == '__main__':
app.run()
That's it! The extension automatically:
- Discovers all your SQLAlchemy models
- Creates appropriate Flask-RESTX models and serializers
- Generates full CRUD API endpoints for each model
- Provides Swagger documentation at
/api/docs
How It Works
flask-api-sqlalchemy analyzes your SQLAlchemy models and automatically creates REST API endpoints with appropriate data validation:
- Model Discovery: The extension finds all SQLAlchemy models in your application
- Type Mapping: SQLAlchemy column types are mapped to appropriate Flask-RESTX field types
- API Generation: CRUD endpoints are created for each model with proper validation
- Documentation: Swagger UI is automatically generated for testing and exploration
Detailed Usage
Model Relationships
The extension supports models with relationships:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref='items')
Generated Endpoints
For each model, the following RESTful endpoints are automatically created:
| HTTP Method | Endpoint | Description | Status Codes |
|---|---|---|---|
| GET | /api/{models}/ | List all resources | 200 OK |
| POST | /api/{models}/ | Create a new resource | 201 Created, 400 Bad Request |
| GET | /api/{models}/{id} | Get a specific resource | 200 OK, 404 Not Found |
| PUT | /api/{models}/{id} | Update a specific resource | 200 OK, 404 Not Found |
| DELETE | /api/{models}/{id} | Delete a specific resource | 204 No Content, 404 Not Found |
Command-Line Interface
This extension includes a helpful CLI for setting up new projects:
# Create a new Flask application with flask-api-sqlalchemy
flask-api-sqlalchemy scaffold --dir myapp
# Show information about models in an existing application
flask-api-sqlalchemy info app:app
Type Mapping
SQLAlchemy column types are automatically mapped to appropriate Flask-RESTX fields:
| SQLAlchemy Type | Flask-RESTX Field |
|---|---|
| Integer | fields.Integer |
| String | fields.String |
| Text | fields.String |
| Boolean | fields.Boolean |
| Date | fields.Date |
| DateTime | fields.DateTime |
| Float | fields.Float |
| ... and many more |
Configuration Options
Configure the extension through Flask application config:
app.config['API_TITLE'] = "My Custom API" # Default: "Flask-SQLAlchemy API"
app.config['API_DESCRIPTION'] = "Custom description" # Default: "Automatically generated API from SQLAlchemy models"
app.config['API_VERSION'] = "1.0"
Data Validation
The extension automatically validates incoming data:
- Required fields (non-nullable columns) are enforced
- Data types are validated according to SQLAlchemy column types
- Helpful error messages are returned for invalid data
Troubleshooting
No Models Found
If no models are discovered, ensure:
- Your models inherit from
db.Model - Models are imported before initializing the API
- The db instance passed to
api.init_app()is the same one used to define your models
Missing Endpoints
Check that:
- The Flask blueprint is registered correctly (happens automatically in
init_app()) - Your app context is active when accessing endpoints
- Names are correctly pluralized in the URL (e.g.,
/api/users/not/api/user/)
License
MIT License
Copyright (c) 2025 Sean McCarthy
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Author Info
Sean McCarthy is Chief Data Scientist at IJACK Technologies Inc, a leading manufacturer of fully-automated pumps to green the oil and gas industry.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flask_api_sqlalchemy-0.1.4.tar.gz.
File metadata
- Download URL: flask_api_sqlalchemy-0.1.4.tar.gz
- Upload date:
- Size: 12.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.2 CPython/3.13.3 Linux/5.15.167.4-microsoft-standard-WSL2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
de708592d8dca568a4519969d7c031d98fdb596b3f1031550a14b1f6e6e74690
|
|
| MD5 |
a59367048b77d56246a9ba603080b9f4
|
|
| BLAKE2b-256 |
8654c9e9cfeebe9a93d90a2f7d44e738ae543802d8c3599fbb85e719b855d531
|
File details
Details for the file flask_api_sqlalchemy-0.1.4-py3-none-any.whl.
File metadata
- Download URL: flask_api_sqlalchemy-0.1.4-py3-none-any.whl
- Upload date:
- Size: 13.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.2 CPython/3.13.3 Linux/5.15.167.4-microsoft-standard-WSL2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a8f165e2d283ceaa61136aefe02f638e4882112a9c9500967c80319af5f02819
|
|
| MD5 |
b2941f8b4388d56ebfdbb312a28db769
|
|
| BLAKE2b-256 |
3efe8e02fe3b9ec75edc744cd30935912662562c4654687848238299abe01ca0
|