Generate production-ready APIs from a simple Markdown specification.
Project description
API Blueprint Generator
Stop writing APIs twice. Write the spec once, get the working code.
๐ Quick Start
Transform this simple Markdown specification:
# Todo API
## Data Models
### Todo
- id: integer (primary key)
- title: string (required)
- completed: boolean (default: false)
- created_at: datetime
## Endpoints
### GET /todos
**Description**: Get all todos
**Response**:
- 200: `{"todos": [...]}`
### POST /todos
**Description**: Create a new todo
**Request Body**:
```json
{
"title": "Buy groceries"
}
Response:
- 201:
{"id": 1, "title": "Buy groceries", "completed": false}
Into a production-ready API in seconds:
```bash
pip install api-blueprint-generator
blueprint generate todo-spec.md --output todo-api
cd todo-api && docker-compose up
Result: A working Flask API with a database, validation, tests, and documentation available at http://localhost:5000.
๐ฏ Why API Blueprint Generator?
The Problem
- Writing API documentation, then implementing the same logic again.
- Manually keeping documentation and code in sync.
- Starting every API project from scratch.
- Inconsistent patterns across team projects.
The Solution
- Single Source of Truth: One Markdown file defines everything.
- Production Ready: The generated code includes tests, validation, and deployment configuration.
- Time Savings: A 70% reduction in API scaffolding time.
- Best Practices: Follows established patterns for security, validation, and structure.
What You Get
๐ your-api/
โโโ ๐ app/
โ โโโ __init__.py # Flask app factory
โ โโโ models.py # SQLAlchemy models
โ โโโ routes/ # Generated endpoints
โ โโโ schemas.py # Request/response validation
โ โโโ middleware.py # Auth & rate limiting
โโโ ๐๏ธ migrations/ # Database migrations
โโโ ๐งช tests/ # Comprehensive test suite
โโโ ๐ณ docker-compose.yml # Local development setup
โโโ ๐ requirements.txt # Project dependencies
โโโ ๐ docs/ # Interactive API documentation
๐ Installation
Using pip (Recommended)
pip install api-blueprint-generator
Using Docker
docker pull blueprintgen/api-generator
docker run -v $(pwd):/workspace blueprintgen/api-generator generate spec.md
From Source
git clone https://github.com/yourusername/api-blueprint-generator.git
cd api-blueprint-generator
pip install -e .
๐ง Usage
Basic Generation
# Generate API from a markdown spec
blueprint generate my-api-spec.md
# Specify the output directory
blueprint generate my-api-spec.md --output my-project
# Use a different backend
blueprint generate my-api-spec.md --backend fastapi
# Include PostgreSQL setup
blueprint generate my-api-spec.md --database postgresql
Configuration File
Create a blueprint.yml file for project defaults:
backend: flask # flask, fastapi
database: postgresql # sqlite, postgresql, mysql
auth_type: jwt # jwt, session, oauth, none
include_tests: true
docker_setup: true
api_prefix: "/api/v1"
cors_enabled: true
rate_limiting: true
Development Workflow
- Generate your API:
blueprint generate api-spec.md --output my-api - Run locally:
cd my-api && docker-compose up --build - Regenerate:
blueprint generate ../api-spec.md --output . --overwrite - Run tests:
python -m pytest tests/ - Deploy:
docker build -t my-api .
๐ Specification Format
Complete Example
# E-commerce API
## Authentication
JWT Bearer token required for protected endpoints.
## Configuration
- Base URL: `/api/v1`
- Rate Limit: 100 requests per minute
- CORS: Enabled for all origins
## Data Models
### User
- id: integer (primary key)
- email: string (unique, required, max_length=254)
- username: string (unique, required, max_length=50)
- password: string (required, min_length=8) [write-only]
- is_active: boolean (default: true)
- created_at: datetime (auto)
- updated_at: datetime (auto)
**Relationships**:
- orders: many Order
### Product
- id: integer (primary key)
- name: string (required, max_length=200)
- description: text (nullable)
- price: decimal (required, precision=10, scale=2)
- stock: integer (default: 0)
- category_id: integer (foreign_key: Category.id)
- created_at: datetime (auto)
**Relationships**:
- category: one Category
- order_items: many OrderItem
### Order
- id: integer (primary key)
- user_id: integer (foreign_key: User.id, required)
- status: string (choices: ['pending', 'confirmed', 'shipped', 'delivered'], default: 'pending')
- total: decimal (precision=10, scale=2)
- created_at: datetime (auto)
**Relationships**:
- user: one User
- order_items: many OrderItem
## Endpoints
### POST /auth/register
**Description**: Register a new user
**Public**: true
**Request Body**:
```json
{
"email": "user@example.com",
"username": "johndoe",
"password": "secretpassword"
}
Response:
- 201:
{"id": 1, "email": "user@example.com", "username": "johndoe"} - 400:
{"error": "Email already exists"}
POST /auth/login
Description: Authenticate user and return JWT token Public: true Request Body:
{
"email": "user@example.com",
"password": "secretpassword"
}
Response:
- 200:
{"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", "user": {...}} - 401:
{"error": "Invalid credentials"}
GET /users/me
Description: Get current user profile Authentication: required Response:
- 200:
{"id": 1, "email": "user@example.com", "username": "johndoe"} - 401:
{"error": "Authentication required"}
GET /products
Description: List products with filtering and pagination Public: true Parameters:
- page: integer (default: 1, min: 1)
- limit: integer (default: 20, min: 1, max: 100)
- category: string (optional)
- min_price: decimal (optional)
- max_price: decimal (optional)
- search: string (optional, searches name and description) Response:
- 200:
{"products": [...], "total": 150, "page": 1, "pages": 8}
POST /products
Description: Create a new product (admin only) Authentication: required Permissions: admin Request Body:
{
"name": "Laptop",
"description": "High-performance laptop",
"price": 999.99,
"stock": 10,
"category_id": 1
}
Response:
- 201:
{"id": 1, "name": "Laptop", ...} - 400:
{"error": "Validation failed", "details": {...}} - 403:
{"error": "Admin access required"}
GET /products/{id}
Description: Get product by ID Public: true Parameters:
- id: integer (path parameter, required) Response:
- 200:
{"id": 1, "name": "Laptop", ...} - 404:
{"error": "Product not found"}
PUT /products/{id}
Description: Update product (admin only) Authentication: required Permissions: admin Parameters:
- id: integer (path parameter, required) Request Body: Same as POST /products Response:
- 200:
{"id": 1, "name": "Updated Laptop", ...} - 404:
{"error": "Product not found"} - 403:
{"error": "Admin access required"}
DELETE /products/{id}
Description: Delete product (admin only) Authentication: required Permissions: admin Parameters:
- id: integer (path parameter, required) Response:
- 204: No content
- 404:
{"error": "Product not found"}
POST /orders
Description: Create a new order Authentication: required Request Body:
{
"items": [
{"product_id": 1, "quantity": 2},
{"product_id": 2, "quantity": 1}
]
}
Response:
- 201:
{"id": 1, "status": "pending", "total": 1999.98, "items": [...]} - 400:
{"error": "Invalid product or insufficient stock"}
GET /orders
Description: Get user's orders Authentication: required Parameters:
- page: integer (default: 1)
- limit: integer (default: 10, max: 50) Response:
- 200:
{"orders": [...], "total": 5, "page": 1}
#### Supported Field Types
| Type | Description | Options |
|:---|:---|:---|
| `integer` | 32-bit integer | `min`, `max` |
| `bigint` | 64-bit integer | `min`, `max` |
| `string` | Variable length text | `min_length`, `max_length`, `pattern` |
| `text` | Long text field | - |
| `boolean` | True/false | - |
| `decimal` | Fixed-point decimal | `precision`, `scale`, `min`, `max` |
| `float` | Floating point | `min`, `max` |
| `datetime` | Date and time | `auto` (auto-populate) |
| `date` | Date only | - |
| `time` | Time only | - |
| `email` | Email address | - |
| `url` | URL | - |
| `uuid` | UUID string | - |
| `json` | JSON object/array | - |
#### Field Options
- `required`: Field must have a value.
- `nullable`: Field can be `null`/`None`.
- `unique`: Value must be unique across the table.
- `default`: Default value for the field.
- `choices`: List of allowed values.
- `primary key`: The primary key field.
- `foreign_key`: Reference to another table.
- `write-only`: Field only accepts input (e.g., passwords).
- `read-only`: Field only in responses (e.g., computed fields).
- `auto`: Auto-populate (e.g., timestamps, UUIDs).
---
### ๐ง Customization
#### Adding Custom Business Logic
Generated routes include clear customization points:
```python
# app/routes/products.py (generated)
@products_bp.route('/', methods=['POST'])
@require_auth
@validate_json(CreateProductSchema)
def create_product():
# Generated validation code
data = request.get_json()
# CUSTOMIZATION POINT: Add your business logic here
# Example: Check inventory, send notifications, etc.
# Generated persistence code
product = Product(**data)
db.session.add(product)
db.session.commit()
return jsonify(product.to_dict()), 201
Custom Templates
Override any generated file by creating a templates directory:
mkdir templates
cp ~/.api-blueprint/templates/routes.py.j2 templates/
# Edit templates/routes.py.j2 with your customizations
blueprint generate spec.md --template-dir templates
Middleware Customization
The app/middleware.py file is generated with customization points for authentication, logging, and more.
๐งช Testing
Generated projects include comprehensive test suites:
# Run all tests
python -m pytest
# Run with coverage
python -m pytest --cov=app tests/
# Run a specific test file
python -m pytest tests/test_products.py
# Run integration tests only
python -m pytest tests/integration/
Generated Test Types:
- Unit Tests: Model validation and business logic.
- Integration Tests: Full API endpoint testing.
- Database Tests: Migration and constraint validation.
- Authentication Tests: Permission and token validation.
- Performance Tests: Response time benchmarks.
๐ Deployment
Local Development
docker-compose up
- API:
http://localhost:5000 - Docs:
http://localhost:5000/docs - Database: PostgreSQL on port
5432
Production Deployment
Docker Container:
docker build -t my-api .
docker run -p 8000:8000 \
-e DATABASE_URL=postgresql://... \
-e JWT_SECRET_KEY=... \
my-api
Environment Variables:
DATABASE_URL: Required connection string.JWT_SECRET_KEY: Required for JWT auth.- Optional:
FLASK_ENV,CORS_ORIGINS,RATE_LIMIT_PER_MINUTE,LOG_LEVEL.
Kubernetes:
- Generated k8s manifests are in
deploy/k8s/. kubectl apply -f deploy/k8s/
Railway/Heroku:
- Generated
Procfileandruntime.txtare included. git push heroku main
๐ก๏ธ Security Features
Built-in Security:
- Input Validation: Pydantic schemas for all endpoints.
- SQL Injection Prevention: SQLAlchemy ORM with parameterized queries.
- CORS Protection: Configurable origin restrictions.
- Rate Limiting: Per-IP and per-user limits.
- JWT Authentication: Secure token-based auth.
- Password Hashing:
bcryptwith salt rounds. - Security Headers: HTTPS enforcement, CSP, etc.
๐ Monitoring & Observability
Generated APIs include monitoring setup:
GET /health(Health check)GET /metrics(Prometheus metrics)GET /info(API version and build info)
Built-in metrics:
- Request count and response times
- Error rates by endpoint
- Database connection pool status
- Authentication success/failure rates
๐ค Contributing
We welcome contributions! See CONTRIBUTING.md for guidelines.
Development Setup
git clone https://github.com/yourusername/api-blueprint-generator.git
cd api-blueprint-generator
pip install -e ".[dev]"
python -m pytest
๐ Examples
Real-World Examples:
- Todo API - Simple CRUD operations
- E-commerce API - Complex relationships and auth
- Blog API - Content management with user roles
- Social Media API - Real-time features and file uploads
- IoT Data API - Time-series data and analytics
Community Templates:
- REST API Best Practices
- Microservice Template
- GraphQL Bridge
- Event-Driven Architecture
๐ Support
- Documentation: Full Documentation, API Specification Guide, Deployment Guide, Customization Guide.
- Getting Help: GitHub Issues, Discord Community, Stack Overflow.
- Commercial Support: Patreon, Enterprise Support.
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- Thanks to all contributors.
- Inspired by the API-first development movement.
- Built with love for the developer community.
๐บ๏ธ Roadmap
Current Version (1.0)
- โ Flask backend generation
- โ SQLite and PostgreSQL support
- โ JWT authentication
- โ Docker deployment
- โ Comprehensive test generation
Next Release (1.1)
- ๐ FastAPI backend option
- ๐ File upload handling
- ๐ WebSocket endpoint support
- ๐ GraphQL schema generation
Future Versions
- ๐ฎ Django REST framework backend
- ๐ฎ Microservice architecture templates
- ๐ฎ OpenAPI 3.1 full compatibility
- ๐ฎ Auto-scaling deployment configs
- ๐ฎ AI-powered API optimization suggestions
Ready to transform your API development workflow?
pip install api-blueprint-generator
echo "# My First API" > api.md
blueprint generate api.md
Join thousands of developers who've already made the switch to specification-first development.
Project details
Release history Release notifications | RSS feed
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 api_blueprint_generator-1.0.0.tar.gz.
File metadata
- Download URL: api_blueprint_generator-1.0.0.tar.gz
- Upload date:
- Size: 48.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
56f266d45de75aeb3c17c97dff588f69db4afeb4547b750f8c9ee01b59ef9f1a
|
|
| MD5 |
0a97209c73f2333e24469193ed63f72c
|
|
| BLAKE2b-256 |
b051f822a73d604c4ef1f97d4e08343823d3c5dcf5281c334003592331551473
|
File details
Details for the file api_blueprint_generator-1.0.0-py3-none-any.whl.
File metadata
- Download URL: api_blueprint_generator-1.0.0-py3-none-any.whl
- Upload date:
- Size: 59.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c8028a8ae6df3ec1eb50e1911bfe0ed2230ae26e26c389a4309cf9d527a39c25
|
|
| MD5 |
a42bc50eabc62ebac02b941fb64317dd
|
|
| BLAKE2b-256 |
a0bf0fff25038ae094df9f0c63788df96c3134952f24ac24aa64609b816c02c8
|