Flext ๐
A lightweight Flask extension that brings Next.js-style API routing to Flask applications. Organize your Flask APIs using file-based routing, just like Next.js!
Features โจ
- ๐ File-based routing similar to Next.js
- ๐ Automatic HTTP method detection from filenames
- ๐ Simple integration with existing Flask apps
- 0๏ธโฃ Zero additional dependencies beyond Flask
- ๐ฏ Convention over configuration
- ๐ง Easy to extend and customize
Installation ๐ฆ
# Currently local installation
git clone https://github.com/napjon/flext
cd flext
pip install -e .
Quick Start ๐
- Create your API structure:
your_app/
โโโ app.py
โโโ api/
โ โโโ hello/
โ โ โโโ get.py
โ โ โโโ post.py
- Write your endpoint in
api/hello/get.py:
def main(request):
return {"message": "Hello World!"}
- Setup your Flask app (
app.py):
from flask import Flask
from flext import Flext
app = Flask(__name__)
app = Flext(app)
if __name__ == '__main__':
app.run(debug=True)
That's it! Your API endpoints are now available at:
GET /api/hello
POST /api/hello
API Endpoint Structure ๐
Each endpoint should have a main function that accepts a Flask request object:
def main(request):
"""
Args:
request (flask.Request): HTTP request object.
Returns:
Response: Any Flask-compatible response
"""
return {"status": "success"}
Supported HTTP Methods ๐
Files are automatically mapped to HTTP methods:
get.py โ GET
post.py โ POST
put.py โ PUT
delete.py โ DELETE
patch.py โ PATCH
Configuration โ๏ธ
Customize Flext behavior during initialization:
app = Flext(
app,
api_dir='custom_api_dir', # Default: 'api'
prefix='/api/v1', # Default: '/api'
debug=True # Default: False
)
Deployment ๐
Traditional Server
pip install gunicorn
gunicorn app:app
Docker
FROM python:3.9-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["gunicorn", "app:app"]
Cloud Functions (GCP)
Modify the entry point for Google Cloud Functions:
# main.py
from flask import Flask
from flext import Flext
app = Flask(__name__)
app = Flext(app)
# For Cloud Functions
def entry_point(request):
return app(request)
Common Patterns ๐
Error Handling
Create a global error handler:
# api/_middleware.py
def handle_errors(app):
@app.errorhandler(404)
def not_found(e):
return {"error": "Not found"}, 404
@app.errorhandler(500)
def server_error(e):
return {"error": "Internal server error"}, 500
Request Validation
Validate incoming requests:
# api/users/post.py
from flask import jsonify
def main(request):
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
required = ['napjon', 'email']
if not all(k in data for k in required):
return jsonify({"error": "Missing required fields"}), 400
return jsonify({"status": "user created"})
Database Integration
Use Flask's application context:
# api/users/get.py
from flask import current_app
def main(request):
db = current_app.config['DB']
users = db.query(...)
return jsonify(users)
Development Guide ๐ ๏ธ
Project Structure
flext/
โโโ flext.py # Main library code
โโโ setup.py # Package setup
โโโ requirements.txt # Dependencies
โโโ tests/ # Test cases
Running Tests
pip install pytest
pytest tests/
Future Development Ideas ๐ก
Middleware Support
- Add support for middleware files (e.g.,
_middleware.py)
- Enable global and route-specific middleware
API Documentation
- Automatic OpenAPI/Swagger documentation generation
- Integration with Flask-RESTX
Hot Reloading
- Implement hot reloading for API routes
- Development server with auto-reload
Type Hints
- Add comprehensive type hints
- Runtime type checking
Route Validation
- Schema validation support
- Pydantic integration
CLI Tool
- Scaffold new API endpoints
- Generate boilerplate code
Contributing ๐ค
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
Development Setup
# Clone repository
git clone https://github.com/napjon/flext
cd flext
# Create virtual environment
python -m venv venv
source venv/bin/activate # or `venv\Scripts\activate` on Windows
# Install dependencies
pip install -r requirements.txt
pip install -r requirements-dev.txt
# Run tests
pytest
Support ๐ฌ
License ๐
MIT License - see LICENSE for details
Acknowledgments ๐
- Inspired by Next.js API routes
- Built on top of Flask
- Made with โค๏ธ by the community