Background Tasks Example - Fastapi Typing CST Test
Loading…
Background Tasks Example — Fastapi Code
Run background tasks after returning a response.
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
with open('log.txt', 'a') as f:
f.write(message + '\n')
@app.post('/send/')
async def send_message(message: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, message)
return { 'message': message }Fastapi Language Guide
FastAPI is a modern, high-performance Python web framework for building APIs with automatic interactive documentation. It emphasizes speed, type hints, and ease of development, leveraging Python 3.7+ features.
Primary Use Cases
- ▸Building RESTful and JSON APIs
- ▸High-performance asynchronous backend
- ▸Microservices architecture
- ▸Data validation and processing APIs
- ▸Integrating with frontend frameworks or machine learning models
Notable Features
- ▸Automatic validation with Pydantic models
- ▸Asynchronous support with async/await
- ▸Interactive API documentation with Swagger UI/ReDoc
- ▸Dependency injection system for modular code
- ▸High performance close to Node.js frameworks
Origin & Creator
FastAPI was created by Sebastián Ramírez in 2018 to provide a fast and developer-friendly Python API framework.
Industrial Note
FastAPI is ideal for projects requiring high-performance async APIs, automatic data validation, and rapid development cycles in Python.