### FastAPI Deployment Examples Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Examples of deploying FastAPI applications to various platforms, including Deta, Fly.io, and AWS Lambda. ```Python # Deta example # https://dev.to/athulcajay/fastapi-deta-ni5 ``` ```Python # Fly.io tutorial # https://fly.io/docs/python/frameworks/fastapi/ ``` ```Python # Fly.io example from Git repo # https://github.com/fly-apps/hello-fastapi ``` ```Python # Heroku step-by-step tutorial # https://tutlinks.com/create-and-deploy-fastapi-app-to-heroku/ ``` ```Python # ML model on Heroku tutorial # https://testdriven.io/blog/fastapi-machine-learning/ ``` ```Python # AWS Lambda example # https://github.com/iwpnd/fastapi-aws-lambda-example ``` ```Python # Google Cloud Run example # https://github.com/anthonycorletti/cloudrun-fastapi ``` ```Python # Vercel example # https://github.com/Snailedlt/Markdown-Videos ``` -------------------------------- ### FastAPI RealWorld Example App (PostgreSQL) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An implementation of the RealWorld example application using FastAPI and PostgreSQL. ```Python fastapi-realworld-example-app: https://github.com/nsidnev/fastapi-realworld-example-app ``` -------------------------------- ### FastAPI CRUD Examples (Async and Sync) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides examples of implementing Create, Read, Update, and Delete operations with FastAPI, offering both asynchronous and synchronous flavors. ```Python fastapi-crud-async: https://github.com/testdrivenio/fastapi-crud-async fastapi-crud-sync: https://github.com/testdrivenio/fastapi-crud-sync ``` -------------------------------- ### Tortoise ORM FastAPI Integration Example Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An example demonstrating the integration of Tortoise ORM, an asyncio ORM inspired by Django, with FastAPI. Includes setup and usage patterns. ```python from fastapi import FastAPI from tortoise import Tortoise, run_async from tortoise.contrib.fastapi import HTTPFastAPI # Define your Tortoise ORM models # class User(Model): # id = fields.IntField(pk=True) # name = fields.CharField(max_length=255) # # def __str__(self): # return self.name # Initialize Tortoise ORM # async def init(): # await Tortoise.init( # db_url="sqlite://:memory:", # modules={"models": ["__main__"]} # ) # await Tortoise.generate_schemas() # Create a FastAPI app using HTTPFastAPI # app = HTTPFastAPI(init) # Example usage: # @app.get("/users/") # async def get_users(): # return await User.all() # if __name__ == "__main__": # run_async(init()) # uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### FastAPI MongoDB RealWorld Example App Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An implementation of the RealWorld example application using FastAPI and MongoDB. ```Python fastapi-mongodb-realworld-example-app: https://github.com/markqiu/fastapi-mongodb-realworld-example-app ``` -------------------------------- ### Prisma Client Python with FastAPI Example Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Shows how to use Prisma Client Python, an auto-generated, type-safe ORM powered by Pydantic, with FastAPI. It supports various databases. ```python from fastapi import FastAPI from prisma import Prisma app = FastAPI() prisma = Prisma() @app.on_event("startup") async def startup(): await prisma.connect() @app.on_event("shutdown") async def shutdown(): await prisma.disconnect() # Example usage: # @app.get("/users/{user_id}") # async def get_user(user_id: str): # user = await prisma.user.find_unique(where={"id": user_id}) # return user ``` -------------------------------- ### GINO with FastAPI Example Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Demonstrates using GINO, a lightweight asynchronous ORM built on SQLAlchemy Core, with FastAPI. It's designed for Python asyncio applications. ```python from fastapi import FastAPI from gino import Gino app = FastAPI() Gino.create_db(app, "postgresql://user:password@host:port/database") # Define your GINO models # class User(Gino.Model): # id = Gino.Integer(primary_key=True) # name = Gino.Unicode() # # # Example usage in an endpoint: # @app.get("/users/{user_id}") # async def get_user(user_id: int): # user = await User.get(user_id) # return user ``` -------------------------------- ### Piccolo ORM with FastAPI Examples Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides examples of using Piccolo, an asynchronous ORM and query builder, with FastAPI. Piccolo supports PostgreSQL and SQLite. ```python from fastapi import FastAPI from piccolo.conf.log import logger from piccolo.engine import PostgresEngine from piccolo_api.fastapi.main import FastAPIRESTEndpoint # Configure your Piccolo engine # engine = PostgresEngine(user='user', password='password', host='host', port=5432, database='database') # Define your Piccolo models # class Movie(Table): # id = IntegerField(primary_key=True) # name = TextField() # year = IntegerField() # Create a FastAPI app # app = FastAPI() # Mount the REST endpoint for your model # app.mount("/movies/", FastAPIRESTEndpoint(Movie, engine=engine)) # This automatically creates endpoints for CRUD operations on the Movie model. ``` -------------------------------- ### FastAPI Full Stack Templates Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md These templates provide a comprehensive starting point for full-stack FastAPI applications, often including databases, frontend frameworks, and deployment tools. ```Python fastapi/full-stack-fastapi-template: FastAPI, React, SQLModel, PostgreSQL, Docker, GitHub Actions, automatic HTTPS. prostomarkeloff/fastapi-tortoise: FastAPI with Tortoise-ORM for database interaction. Buuntu/fastapi-react: FastAPI, TypeScript, Docker, PostgreSQL, and React. mongodb-labs/full-stack-fastapi-mongodb: FastAPI, MongoDB, Docker, Celery, React frontend. ``` -------------------------------- ### Manage FastAPI (CLI) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A Command Line Interface (CLI) tool for generating and managing FastAPI projects. It simplifies project setup and maintenance. ```python # Example CLI command (conceptual) # manage-fastapi create my_project ``` -------------------------------- ### Bitcart Platform Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A platform for merchants, users, and developers offering easy setup and usage for various applications. ```Python bitcart: https://github.com/bitcart/bitcart ``` -------------------------------- ### FastAPI with Celery, RabbitMQ, and Redis Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A minimal example showcasing FastAPI integrated with Celery for task queuing, RabbitMQ as a message broker, and Redis as a Celery backend. Includes Flower for monitoring. ```Python fastapi-celery: https://github.com/GregaVrbancic/fastapi-celery ``` -------------------------------- ### FastAPI Tutorials and Articles Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A collection of tutorials and articles covering various aspects of FastAPI development, including asynchronous operations, security, machine learning model serving, testing, and more. ```APIDOC Async SQLAlchemy with FastAPI: https://stribny.name/posts/fastapi-asyncalchemy/ Build and Secure an API in Python with FastAPI: https://blog.yezz.me/blog/Build-and-Secure-an-API-in-Python-with-FastAPI Deploy Machine Learning Models with Keras, FastAPI, Redis and Docker: https://medium.com/analytics-vidhya/deploy-machine-learning-models-with-keras-fastapi-redis-and-docker-4940df614ece Developing and Testing an Asynchronous API with FastAPI and Pytest: https://testdriven.io/blog/fastapi-crud/ FastAPI for Flask Users: https://amitness.com/posts/fastapi-vs-flask Getting started with GraphQL in Python with FastAPI and Ariadne: https://blog.yezz.me/blog/Getting-started-with-GraphQL-in-Python-with-FastAPI-and-Ariadne Implementing FastAPI Services – Abstraction and Separation of Concerns: https://camillovisini.com/coding/abstracting-fastapi-services Introducing FARM Stack - FastAPI, React, and MongoDB: https://www.mongodb.com/developer/languages/python/farm-stack-fastapi-react-mongodb/ Multitenancy with FastAPI, SQLAlchemy and PostgreSQL: https://mergeboard.com/blog/6-multitenancy-fastapi-sqlalchemy-postgresql/ Porting Flask to FastAPI for ML Model Serving: https://www.pluralsight.com/tech-blog/porting-flask-to-fastapi-for-ml-model-serving/ Real-time data streaming using FastAPI and WebSockets: https://stribny.name/posts/real-time-data-streaming-using-fastapi-and-websockets/ Running FastAPI applications in production: https://stribny.name/posts/fastapi-production/ Serving Machine Learning Models with FastAPI in Python: https://medium.com/@8B_EC/tutorial-serving-machine-learning-models-with-fastapi-in-python-c1a27319c459 Streaming video with FastAPI: https://stribny.name/posts/fastapi-video/ Using Hypothesis and Schemathesis to Test FastAPI: https://testdriven.io/blog/fastapi-hypothesis/ ``` -------------------------------- ### Astrobase: Simple, Fast, Secure Deployments Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A tool for simple, fast, and secure deployments to any environment. ```Rust astrobase: https://github.com/anthonycorletti/astrobase ``` -------------------------------- ### FastAPI Official Resources Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Links to the official documentation, tutorial, source code repository, and community Discord server for FastAPI. ```APIDOC Documentation: https://fastapi.tiangolo.com/ Tutorial: https://fastapi.tiangolo.com/tutorial/ Source Code: https://github.com/fastapi/fastapi Discord: https://discord.com/invite/VQjSZaeJmf ``` -------------------------------- ### FastAPI Best Practices Repository Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A collection of best practices for developing FastAPI applications, maintained in a GitHub repository. ```Markdown # FastAPI Best Practices This repository contains a collection of best practices for building robust and scalable FastAPI applications. ``` -------------------------------- ### FastAPI Talks and Presentations Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Video resources from conferences and podcasts discussing FastAPI, its features, and use cases, including building APIs for machine learning models and from the ground up. ```APIDOC PyConBY 2020: Serve ML models easily with FastAPI: https://www.youtube.com/watch?v=z9K5pwb0rt8 PyCon UK 2019: FastAPI from the ground up: https://www.youtube.com/watch?v=3DLwPcrE5mA Build The Next Generation Of Python Web Applications With FastAPI: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ FastAPI on PythonBytes: https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855 ``` -------------------------------- ### FastAPI with SQLAlchemy, Alembic, and Arq Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A funding and monetization platform for developers built using FastAPI, SQLAlchemy for ORM, Alembic for database migrations, and Arq for asynchronous task queues. ```Python Polar: https://github.com/polarsource/polar ``` -------------------------------- ### FastAPI vs. Flask Comparisons Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Articles that compare FastAPI with Flask, highlighting reasons for switching to FastAPI for production machine learning and general web development. ```APIDOC FastAPI has Ruined Flask Forever for Me: https://medium.com/data-science/fastapi-has-ruined-flask-forever-for-me-73916127da Why we switched from Flask to FastAPI for production machine learning: https://medium.com/@calebkaiser/why-we-switched-from-flask-to-fastapi-for-production-machine-learning-765aab9b3679 FastAPI for Flask Users: https://amitness.com/posts/fastapi-vs-flask Porting Flask to FastAPI for ML Model Serving: https://www.pluralsight.com/tech-blog/porting-flask-to-fastapi-for-ml-model-serving/ ``` -------------------------------- ### FastAPI with Observability (Tempo, Prometheus, Loki) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Demonstrates how to integrate observability pillars (Traces, Metrics, Logs) into a FastAPI application using OpenTelemetry, OpenMetrics, Prometheus, Loki, and Grafana. ```Python fastapi-observability: https://github.com/Blueswen/fastapi-observability ``` -------------------------------- ### FastAPI ML Model Serving Skeletons Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Templates designed for serving machine learning models using FastAPI, facilitating production-ready deployments. ```Python eightBEC/fastapi-ml-skeleton: Skeleton app to serve machine learning models production-ready. microsoft/cookiecutter-spacy-fastapi: Quick deployments of spaCy models with FastAPI. ``` -------------------------------- ### FastAPI Project Generators and Boilerplates Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Tools and templates for scaffolding FastAPI projects with various configurations and features, including ORMs, CI/CD, and cloud integrations. ```Python arthurhenrique/cookiecutter-fastapi: FastAPI projects using Machine Learning, Poetry, Azure Pipelines and pytest. vutran1710/YeomanPywork: Yeoman generator to scaffold a FastAPI app. leosussan/fastapi-gino-arq-uvicorn: High-performance async REST API with FastAPI, GINO, Arq, Uvicorn, Redis, and PostgreSQL. rednafi/fastapi-nano: Simple FastAPI template with factory pattern architecture. s3rius/FastAPI-template: Flexible, lightweight FastAPI project generator with SQLAlchemy, multiple databases, CI/CD, Docker, and Kubernetes support. openapi-generators/openapi-python-client: Generate modern FastAPI Python clients from OpenAPI. cloudrun-fastapi: Boilerplate for API building with FastAPI, SQLModel, and Google Cloud Run. firestore-fastapi: Boilerplate for API building with FastAPI and Google Cloud Firestore. jonra1993/fastapi-alembic-sqlmodel-async: FastAPI, Alembic, and async SQLModel as ORM. mirzadelic/fastapi-starter-project: FastAPI, SQLModel, Alembic, Pytest, Docker, GitHub Actions CI. max-pfeiffer/uvicorn-poetry-fastapi-project-template: Cookiecutter template for FastAPI with Uvicorn, Poetry, Docker, Kubernetes, supporting AMD64 and ARM64. ``` -------------------------------- ### FastAPI Websocket Broadcast Demo Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A simple demonstration of a websocket broadcast functionality using FastAPI. ```Python fastapi-websocket-broadcast: https://github.com/kthwaite/fastapi-websocket-broadcast ``` -------------------------------- ### FastAPI Docker Images Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Pre-built Docker images optimized for running FastAPI applications, often including Uvicorn, Gunicorn, and Poetry for dependency management. ```Docker br3ndonland/inboard: Docker images to power your FastAPI apps. tiangolo/uvicorn-gunicorn-fastapi-docker: Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications. max-pfeiffer/uvicorn-gunicorn-poetry: Docker image with Gunicorn using Uvicorn workers, Poetry for dependency management, supporting AMD64 and ARM64. max-pfeiffer/uvicorn-poetry: Docker image with Uvicorn ASGI server for running Python web applications on Kubernetes, using Poetry, supporting AMD64 and ARM64. ``` -------------------------------- ### msgpack-asgi Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Handles automatic MessagePack content negotiation for ASGI applications, including FastAPI. It allows for efficient binary data serialization. ```python from msgpack_asgi import MessagePackMiddleware app.add_middleware(MessagePackMiddleware, ...) ``` -------------------------------- ### Nemo Backend Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A backend project for Nemo, aiming to enhance productivity. ```Python nemo-backend: https://github.com/harshitsinghai77/nemo-backend ``` -------------------------------- ### OPAL (Open Policy Administration Layer) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Real-time authorization updates built on Open-Policy, utilizing FastAPI, Typer, and FastAPI WebSocket pub/sub for managing policies in cloud-native environments. ```Python opal: https://github.com/authorizon/opal ``` -------------------------------- ### Bali Framework for Cloud Native Microservices Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A framework designed to simplify Cloud Native Microservices development, built on FastAPI and gRPC. ```Python bali-framework: https://github.com/bali-framework/bali ``` -------------------------------- ### FuturamaAPI: REST and GraphQL with WebSockets, SSE, Callbacks Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A REST and GraphQL playground built with best practices, featuring WebSockets, Server-Sent Events (SSE), callbacks, and secret messages, all powered by FastAPI. ```Python futuramaapi: https://github.com/koldakov/futuramaapi ``` -------------------------------- ### FastAPI Utilities (Class-based Views, Periodic Tasks) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A collection of reusable utilities for FastAPI, including support for class-based views, periodic tasks, timing middleware, SQLAlchemy session management, and OpenAPI spec simplification. ```python from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from fastapi_utils.tasks import repeat_every router = InferringRouter() @cbv(router) class ItemAPI: def __init__(self, request: Request): self.request = request @router.get("/items/{item_id}") def get_item(self, item_id: int): return {"item_id": item_id} @repeat_every(seconds=60) def periodic_task(): print("This task runs every minute.") app.include_router(router) ``` -------------------------------- ### FastAPI Plugins (Redis, Scheduler) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides plugins for FastAPI, including Redis integration and task scheduling capabilities. These can be used to manage background tasks and data storage. ```python from fastapi_plugins import RedisPlugin, SchedulerPlugin app = FastAPI() app.add_plugin(RedisPlugin()) app.add_plugin(SchedulerPlugin()) # Example usage (conceptual): # async def my_task(): # await redis_plugin.set("mykey", "myvalue") # scheduler_plugin.add_task(my_task, interval=60) ``` -------------------------------- ### PyPika SQL Query Builder Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md PyPika is a Python library for building SQL queries. It allows you to construct complex SQL statements programmatically. ```python from pypika import Query, Table # Define your table # users = Table('users') # Build a SELECT query # query = Query.from_(users).select(users.id, users.name) # Build an INSERT query # query = Query.into(users).insert(1, 'John Doe') # Build an UPDATE query # query = Query.update(users).set(users.name, 'Jane Doe').where(users.id == 1) # Convert to string # print(str(query)) ``` -------------------------------- ### FastAPI MQTT Integration Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An extension for integrating the MQTT protocol with FastAPI applications. This allows FastAPI applications to act as MQTT clients or brokers. ```python from fastapi import FastAPI from fastapi_mqtt import MQTT app = FastAPI() mqtt = MQTT(app) @mqtt.on_connect() def connect(client, flags, rc, properties): print(f"Connected: {rc}") client.subscribe("test/topic") @mqtt.on_message() def message(client, topic, payload, qos, properties): print(f"Received message: {payload.decode()} on topic {topic}") @app.post("/publish/") async def publish_message(message: str): await mqtt.publish("test/topic", payload=message) return {"message": "Message published"} ``` -------------------------------- ### Fastapi-SQLA for FastAPI and SQLAlchemy Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An extension for FastAPI that integrates SQLAlchemy, offering support for pagination, asyncio, and pytest. It simplifies common database operations. ```python from fastapi import FastAPI from fastapi_sqla import setup_async_session from sqlalchemy.ext.asyncio import create_async_engine app = FastAPI() # Configure your async engine # engine = create_async_engine("postgresql+asyncpg://user:password@host:port/database") # Setup the async session for FastAPI # setup_async_session(app, engine) # Example usage: # @app.get("/users/") # async def get_users(session: AsyncSession = Depends(async_session)): # users = await session.execute(select(User)).scalars().all() # return users ``` -------------------------------- ### FastAPI, React+RxJs, Neo4j, PostgreSQL, Redis Social Network Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A small social network built using FastAPI for the backend, React with RxJs for the frontend, and Neo4j, PostgreSQL, and Redis for data storage and caching. ```Python Bunnybook: https://github.com/pietrobassi/bunnybook ``` -------------------------------- ### FastAPI Event Dispatching and Handling Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Libraries for asynchronous event dispatching and handling in FastAPI and Starlette. These facilitate building event-driven architectures. ```python from fastapi_events.dispatcher import dispatch from fastapi_events.typing import Event async def handle_event(event: Event): print(f"Received event: {event}") @app.post("/trigger-event/") async def trigger_event(): await dispatch("user_created", payload={"user_id": 123}) return {"message": "Event dispatched"} ``` -------------------------------- ### Markdown Videos API Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An API service for generating thumbnails to be embedded within markdown content. ```Python markdown-videos: https://github.com/Snailedlt/Markdown-Videos ``` -------------------------------- ### FastAPI Profiler (Middleware) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A FastAPI middleware that integrates with pyinstrument to profile service performance. It helps identify performance bottlenecks in FastAPI applications. ```python from fastapi_profiler.middleware import ProfilerMiddleware app.add_middleware(ProfilerMiddleware, ...) # Configuration details would follow ``` -------------------------------- ### Mailer Micro-service Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A straightforward mailer micro-service designed for static websites. ```Python mailer: https://github.com/rclement/mailer ``` -------------------------------- ### TermPair: View and Control Terminals via Browser Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Enables viewing and controlling terminals directly from a web browser with end-to-end encryption, built using FastAPI. ```Python termpair: https://github.com/cs01/termpair ``` -------------------------------- ### FastAPI Dependency Injection Utilities Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Tools to use FastAPI's dependency injection system outside of route handlers, such as in CLI tools, background tasks, or workers. This promotes cleaner code and better testability. ```python from fastapi_injectable import Injectable, inject class MyService: def __init__(self, value: int): self.value = value @injectable() def get_my_service() -> MyService: return MyService(value=42) @app.get("/service") async def use_service(my_service: MyService = Depends(get_my_service)): return {"service_value": my_service.value} ``` -------------------------------- ### FastAPI Client Generator (OpenAPI) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Creates a mypy- and IDE-friendly API client from an OpenAPI specification. This tool helps in generating client-side code for interacting with FastAPI services. ```openapi OpenAPI Specification -> FastAPI Client Generation ``` -------------------------------- ### FastAPI Websocket Pub/Sub and RPC Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Enables the classic publish/subscribe pattern and bidirectional JSON RPC over WebSockets for FastAPI applications, making real-time communication accessible and scalable. ```python from fastapi import FastAPI from fastapi_websocket_pubsub import PubSubEndpoint app = FastAPI() app.mount("/pubsub", PubSubEndpoint()) # Clients can connect to ws://your-domain/pubsub # Publish: await PubSubEndpoint.publish(topic='my_topic', message='hello') # Subscribe: client subscribes to 'my_topic' ``` ```python from fastapi import FastAPI from fastapi_websocket_rpc import WebSocketRPCEndpoint, rpc_method app = FastAPI() class MyRPCHandler: @rpc_method def add(self, a: int, b: int) -> int: return a + b app.mount("/rpc", WebSocketRPCEndpoint(MyRPCHandler())) # Clients can call methods like: rpc.call("add", [5, 3]) ``` -------------------------------- ### FastAPI with GraphQL and JWT Authentication Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A simple API for authentication and login using GraphQL and JSON Web Tokens (JWT), built with FastAPI. ```Python JeffQL: https://github.com/yezz123/JeffQL/ ``` -------------------------------- ### Sprites as a Service Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A service for generating personalized 8-bit avatars using Cellular Automata, built with FastAPI. ```Python sprites-as-a-service: https://github.com/ljvmiranda921/sprites-as-a-service ``` -------------------------------- ### FastAPI JSON-RPC Server Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Implementation of a JSON-RPC server utilizing FastAPI. ```Python fastapi-jsonrpc: https://github.com/smagafurov/fastapi-jsonrpc ``` -------------------------------- ### FastAPI CRUD with OAuth2PasswordBearer Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An API for creating a simple blog and performing CRUD operations, secured with OAuth2PasswordBearer authentication. ```Python DogeAPI: https://github.com/yezz123/DogeAPI ``` -------------------------------- ### OpenTelemetry FastAPI Instrumentation Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides automatic and manual instrumentation for FastAPI web frameworks within the OpenTelemetry ecosystem. It instruments HTTP requests served by FastAPI applications. ```python from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor app = FastAPI() FastAPIInstrumentor().instrument(app=app) # Traces will be automatically generated for incoming requests. ``` -------------------------------- ### FastAPI Listing API Design Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A library for designing and building listing APIs with FastAPI. It includes features like query pagination, sorting, and Django-admin-like filtering, simplifying the creation of complex data listing endpoints. ```python from fastapi import FastAPI from fastapi_listing import Listing, ListingQuery app = FastAPI() @app.get("/users/", response_model=Listing[User]) def get_users(query: ListingQuery = Depends()): # Assume 'db' is your database session # users = db.query(User).options(load_only(User.name, User.email)).all() # return Listing.from_list(users, query) pass ``` -------------------------------- ### FastAPI Opentracing and Tracing Middleware Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Middleware and database tracing support for implementing OpenTracing in FastAPI applications. This helps in monitoring and debugging distributed systems. ```python from fastapi import FastAPI from fastapi_opentracing import OpenTracingMiddleware app = FastAPI() app.add_middleware(OpenTracingMiddleware) # For database tracing, specific integrations might be needed depending on the ORM. ``` ```python from starlette_opentracing import OpenTracingMiddleware app.add_middleware(OpenTracingMiddleware) ``` -------------------------------- ### FastAPI Templating Engine Integrations Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Integrations for using template languages like Jinja and Chameleon with FastAPI. These libraries allow for server-side rendering of HTML templates. ```python from fastapi import FastAPI from fastapi_jinja import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def read_root(request: Request): return templates.TemplateResponse("index.html", {"request": request, "message": "Hello, FastAPI!"}) ``` ```python from fastapi import FastAPI from fastapi_chameleon import Chameleon app = FastAPI() app.mount("/", Chameleon(app, template_dir="templates")) # In your templates/index.html (Chameleon syntax): # # #

${message}

# # ``` -------------------------------- ### Databases Async SQL Query Builder Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Databases is an async SQL query builder that works with SQLAlchemy Core's expression language. It provides a clean interface for database operations. ```python from databases import Database from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String # Define your database URL # DATABASE_URL = "postgresql://user:password@host:port/database" # Create a database instance # database = Database(DATABASE_URL) # Define metadata and table # metadata = MetaData() # users = Table( # "users", # metadata, # Column("id", Integer, primary_key=True), # Column("name", String), # Column("email", String) # ) # Example usage: # async def get_users(): # query = users.select() # return await database.fetch_all(query) # To run this, you would typically integrate it within a FastAPI application: # @app.on_event("startup") # async def startup(): # await database.connect() # @app.on_event("shutdown") # async def shutdown(): # await database.disconnect() ``` -------------------------------- ### Dispatch: Security Incident Management Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A system for managing security incidents, developed by Netflix. ```Go dispatch: https://github.com/Netflix/dispatch ``` -------------------------------- ### Jupyter Notebook REST API Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Enables running Jupyter notebooks as RESTful API endpoints. This allows for exposing notebook computations as services. ```python # Conceptual representation of running notebooks as APIs # Specific implementation details would depend on the library ``` -------------------------------- ### Strawberry GraphQL Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A Python GraphQL library built on dataclasses, providing a modern and type-safe way to implement GraphQL APIs. ```python import strawberry from fastapi import FastAPI from strawberry.fastapi import GraphQLRouter @strawberry.type class Query: @strawberry.field def hello(self) -> str: return "Hello World" graphql_app = GraphQLRouter(Query) app = FastAPI() app.mount("/graphql", graphql_app) # Access GraphQL endpoint at /graphql ``` -------------------------------- ### Redis Streams FastAPI Chat Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A simple chat application backend using Redis Streams, WebSockets, Asyncio, and FastAPI/Starlette. ```Python redis-streams-fastapi-chat: https://github.com/leonh/redis-streams-fastapi-chat ``` -------------------------------- ### FastAPI SQLAlchemy Integration Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides simple integration between FastAPI and SQLAlchemy, a popular SQL toolkit and Object Relational Mapper for Python. ```python from fastapi_sqlalchemy import DBSession # Assuming you have a SQLAlchemy engine configured # engine = create_engine("postgresql://user:password@host:port/database") # Create a DBSession instance db_session = DBSession(engine) # Example usage in a FastAPI endpoint: # @app.get("/items/") # async def read_items(): # items = db_session.query(Item).all() # return items ``` -------------------------------- ### Slackers: Slack Webhooks API Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An API service for handling Slack webhooks. ```Python slackers: https://github.com/uhavin/slackers ``` -------------------------------- ### FastAPI Cache Implementations Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides caching solutions for FastAPI, supporting various backends like Redis, Memcached, DynamoDB, and in-memory storage. These libraries help cache responses and function results to improve performance. ```python from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend app.add_event_handler("startup", lambda: FastAPICache.init(RedisBackend(), prefix="fastapi-cache")) app.add_event_handler("shutdown", lambda: FastAPICache.clear()) @app.get("/items/{item_id}") @FastAPICache.cache() async def read_item(item_id: int): # ... your logic ... pass ``` ```python from fastapi_cache.decorator import cache @cache(expire=60) def get_data(): # ... your logic ... pass ``` -------------------------------- ### FastAPI Pagination Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A library providing easy-to-use pagination for FastAPI APIs. It simplifies the process of returning paginated lists of resources. ```python from fastapi import FastAPI from fastapi_pagination import paginate, Page from typing import List app = FastAPI() @app.get("/items/", response_model=Page[Item]) def get_items(): # Assume 'all_items' is a list of your items # return paginate(all_items) pass ``` -------------------------------- ### Mangum Adapter for AWS Lambda Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Mangum is an adapter for running ASGI applications, such as FastAPI, with AWS Lambda and API Gateway. It allows you to deploy your FastAPI applications in a serverless environment. ```Python from mangum import Mangum from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} handler = Mangum(app) ``` -------------------------------- ### FastAPI Service Utilities Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A generator for creating API services with FastAPI. It helps in structuring and generating boilerplate code for API services. ```python # This library typically provides CLI tools for generation. # Example command (conceptual): # fastapi-service-utils create my_api_service --template fastapi ``` -------------------------------- ### FastAPI Socket.IO Integration Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Facilitates easy integration of Socket.IO with FastAPI applications, enabling real-time, bidirectional communication. ```python from fastapi import FastAPI from fastapi_socketio import SocketManager app = FastAPI() socket_manager = SocketManager(app=app) @app.sio.on("connect") def handle_connect(sid, *args, **kwargs): print(f"Client connected: {sid}") @app.sio.on("message") async def handle_message(sid, message): print(f"Message from {sid}: {message}") await app.sio.emit("response", "Message received!") ``` -------------------------------- ### FastAPI Authentication and Authorization Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A variety of libraries for handling authentication and authorization in FastAPI applications, including OAuth2, JWT, Azure AD integration, and role-based permissions. ```Python AuthX: https://github.com/yezz123/AuthX FastAPI Auth: https://github.com/dmontagu/fastapi-auth FastAPI Azure Auth: https://github.com/Intility/fastapi-azure-auth FastAPI Cloud Auth: https://github.com/tokusumi/fastapi-cloudauth FastAPI Login: https://github.com/maxrdu/fastapi_login FastAPI JWT Auth: https://github.com/IndominusByte/fastapi-jwt-auth FastAPI Permissions: https://github.com/holgi/fastapi-permissions FastAPI Security: https://github.com/jacobsvante/fastapi-security FastAPI Simple Security: https://github.com/mrtolkien/fastapi_simple_security FastAPI Users: https://github.com/fastapi-users/fastapi-users ``` -------------------------------- ### FastAPI Feature Flags Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A simple implementation of feature flags for FastAPI applications. This allows for enabling or disabling features dynamically without redeploying the application. ```python from fastapi_featureflags import FeatureFlags feature_flags = FeatureFlags(config_path="features.yaml") @app.get("/feature") async def get_feature_status(request: Request): if feature_flags.is_enabled("new_feature", request): return {"feature": "enabled"} else: return {"feature": "disabled"} ``` -------------------------------- ### FastAPI Admin Panels Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A collection of admin panel extensions for FastAPI, facilitating CRUD operations and providing user interfaces for data management. Some extensions are ORM-specific. ```Python FastAPI Admin: https://github.com/fastapi-admin/fastapi-admin FastAPI Amis Admin: https://github.com/amisadmin/fastapi-amis-admin Piccolo Admin: https://github.com/piccolo-orm/piccolo_admin SQLAlchemy Admin: https://github.com/aminalaee/sqladmin Starlette Admin: https://github.com/jowilf/starlette-admin ``` -------------------------------- ### SQLModel for FastAPI and Databases Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md SQLModel is a library for interacting with SQL databases using Python objects, built on Pydantic and SQLAlchemy. It's ideal for FastAPI applications. ```python from fastapi import FastAPI from sqlmodel import Field, SQLModel, create_engine, Session # Define your SQLModel # class Hero(SQLModel, table=True): # id: int | None = Field(default=None, primary_key=True) # name: str = Field(index=True) # secret_name: str # age: int | None = Field(default=None, index=True) # Create engine and tables # engine = create_engine("sqlite:///database.db") # def create_db_and_tables(): # SQLModel.metadata.create_all(engine) # Initialize FastAPI # app = FastAPI() # Example usage: # @app.post("/heroes/") # def create_hero(hero: Hero): # with Session(engine) as session: # session.add(hero) # session.commit() # session.refresh(hero) # return hero ``` -------------------------------- ### Prometheus FastAPI Instrumentator Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A configurable and modular Prometheus instrumentator for FastAPI applications. It exposes metrics about your API's performance and usage. ```python from fastapi import FastAPI from prometheus_fastapi_instrumentator import Instrumentator app = FastAPI() Instrumentator().instrument(app=app).expose(app, include_in_schema=False) # Metrics will be available at /metrics endpoint. ``` -------------------------------- ### FastAPI Code Generator (OpenAPI) Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Generates a FastAPI application from an OpenAPI file, facilitating schema-driven development. It takes an OpenAPI specification as input and produces FastAPI code. ```openapi OpenAPI Specification -> FastAPI Code Generation ``` -------------------------------- ### FastAPIwee with PeeWee Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A simple way to create REST APIs based on PeeWee models. PeeWee is a simple and expressive ORM for Python. ```python from fastapi_wee import FastAPIwee from peewee import * # Define your PeeWee model # db = SqliteDatabase('my_database.db') # class User(Model): # name = CharField() # email = CharField(unique=True) # # class Meta: # database = db # Initialize FastAPIwee with your PeeWee model # app = FastAPI() # api = FastAPIwee(app, User) # This automatically creates endpoints for CRUD operations on the User model. ``` -------------------------------- ### Universities API Service Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md An API service providing information for over 9600 universities worldwide. ```Python universities: https://github.com/ycd/universities ``` -------------------------------- ### FastAPI Mail Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md A lightweight mail system for FastAPI, designed for sending emails and attachments, supporting both individual and bulk sending. It simplifies email integration. ```python from fastapi_mail import FastMail, MessageSchema, ConnectionConfig conf = ConnectionConfig(...) fm = FastMail(conf) message = MessageSchema(subject='Test Email', recipients=['test@example.com'], body='This is a test email.') await fm.send_message(message) ``` -------------------------------- ### FastAPI Versioning Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Provides functionality for API versioning in FastAPI applications. This allows for managing different versions of your API endpoints. ```python # Example usage for versioning from fastapi_versioning import VersionedFastAPI app = VersionedFastAPI(app, ...) ``` -------------------------------- ### Starlette Prometheus Integration Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Prometheus integration for Starlette and FastAPI applications. This library helps in collecting and exposing Prometheus metrics. ```python from starlette.applications import Starlette from starlette_exporter import PrometheusExporter, handle_metrics app = Starlette() exporter = PrometheusExporter(app) # Add metrics endpoint app.add_route("/metrics", handle_metrics(exporter)) # Metrics are automatically collected for requests. ``` -------------------------------- ### PynamoDB for Amazon DynamoDB Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md PynamoDB provides a Pythonic interface to Amazon's DynamoDB, allowing you to interact with DynamoDB tables and items using Python objects. ```python from pynamodb.models import Model from pynamodb.attributes import UnicodeAttribute, NumberAttribute # Define your DynamoDB model # class UserModel(Model): # class Meta: # table_name = "Users" # region = "us-east-1" # host = "http://localhost:8000" # For local DynamoDB # # user_id = UnicodeAttribute(hash_key=True) # name = UnicodeAttribute() # age = NumberAttribute(null=True) # Example usage: # async def create_user(user_id: str, name: str, age: int): # await UserModel.create(user_id=user_id, name=name, age=age) # To integrate with FastAPI, you would typically call these functions within endpoints. ``` -------------------------------- ### Pydantic-SQLAlchemy Model Conversion Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md This utility helps convert SQLAlchemy models to Pydantic models, simplifying data validation and serialization in FastAPI applications. ```python from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from pydantic_sqlalchemy import SQLAlchemyBase, SQLAlchemyModel Base = declarative_base() # Define your SQLAlchemy model # class UserSQLA(Base): # __tablename__ = "users" # id = Column(Integer, primary_key=True) # name = Column(String) # email = Column(String) # Convert to Pydantic model # class UserPydantic(SQLAlchemyModel): # class Meta: # model = UserSQLA # exclude = {"id"} # Optionally exclude fields # Now you can use UserPydantic in your FastAPI endpoints for request/response validation. ``` -------------------------------- ### Saffier ORM with FastAPI Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Saffier ORM is designed to be a comprehensive ORM for Python, with seamless integration into FastAPI applications. It leverages Pydantic for validation. ```python from fastapi import FastAPI from saffier import Sapphire, SapphireMeta # Define your Saffier model # class User(Sapphire, metaclass=SapphireMeta): # id: int # name: str # email: str # # class Meta: # bind = "sqlite:///db.sqlite" # registry = None # table = "users" # Initialize FastAPI # app = FastAPI() # Example usage: # @app.post("/users/") # async def create_user(user_data: dict): # user = await User.create(**user_data) # return user ``` -------------------------------- ### Ormar with FastAPI Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Ormar is an asynchronous ORM that uses Pydantic validation and integrates directly with FastAPI. It supports Alembic migrations. ```python from fastapi import FastAPI from ormar import Ormar from pydantic import BaseModel app = FastAPI() # Define your Ormar model # class User(Ormar): # id: int # name: str # email: str # # class Meta: # database = ... # SQLAlchemy database instance # tablename = "users" # Define your Pydantic model for request/response # class UserCreate(BaseModel): # name: str # email: str # Example usage: # @app.post("/users/") # async def create_user(user: UserCreate): # await User.objects.create(**user.dict()) # return user ``` -------------------------------- ### FastAPI Request ID and Context Middleware Source: https://github.com/mjhea0/awesome-fastapi/blob/main/README.md Middleware for managing request IDs and context within FastAPI and Starlette applications. These tools are crucial for logging and tracing requests across different parts of an application. ```python from asgi_correlation_id import CorrelationIdMiddleware app.add_middleware(CorrelationIdMiddleware) # In your logging setup: import logging from asgi_correlation_id import correlation_id logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info(f"Request ID: {correlation_id.get()}") ``` ```python from starlette_context import middleware, plugins app.add_middleware(middleware.ContextMiddleware, plugins=(plugins.CorrelationIdPlugin(),)) # Accessing context data: from starlette_context import context async def get_request_data(): request_id = context.get('correlation_id') return {"request_id": request_id} ```