SlideShare a Scribd company logo
5
Most read
7
Most read
9
Most read
Samuel Folasayo
Boost Your API with Asynchronous
Programming in FastAPI
Implementing Async Programming for High-Performance APIs
Joe Nyirenda
Learning Objectives
● Understand the fundamentals of asynchronous programming
● Learn how to set up a FastAPI environment for async development
● Use async libraries for HTTP requests, database operations, and file handling
● Implement background tasks to enhance API responsiveness
● Write and test async endpoints effectively using FastAPI's test client
● Apply best practices to avoid common pitfalls in async programming
Overview
What is Asynchronous Programming?
A programming model that allows operations to execute non-blockingly
Ideal for I/O-bound tasks like HTTP requests, database queries, and file operations
Synchronous vs Asynchronous Programming
Synchronous: One task at a time; blocks
the next task
Asynchronous: Tasks can overlap,
improves scalability and resource
usage
Why FastAPI?
Built on Starlette and Pydantic
Natively supports async/await syntax for optimal performance
Designed for high-concurrency and minimal latency
Setting Up FastAPI for Async Development
Environment Setup
Install FastAPI for async web serving:
pip install “fastapi[standard]”
Writing an Async Endpoint
Basic example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
Key Points:
Use async def for non-blocking functions
Use await when calling async libraries
Asynchronous Libraries for FastAPI
Why Async Libraries Matter
Using synchronous libraries in an async app blocks the event loop
Leads to poor scalability and performance
Async HTTP Requests
Use httpx instead of requests:
import httpx
@app.get("/external-api" )
async def call_external_api ():
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com/api" )
return response.json()
Asynchronous Libraries for FastAPI
Async Database Operations
Use async ORMs like Tortoise ORM or SQLAlchemy 1.4:
from tortoise import Tortoise
await Tortoise.init(...)
results = await MyModel.filter( name="example")
Async File Operations
Use aiofiles for non-blocking file I/O:
import aiofiles
async with aiofiles.open("file.txt", mode="r") as file:
content = await file.read()
Enhancing Performance with Async Background Tasks
Background Tasks in FastAPI
Ideal for long-running tasks (e.g., sending emails, processing data)
Example: Sending an Email
from fastapi import BackgroundTasks
# Placeholder function
def send_email(email: str, message: str):
print(f"Sending email to {email}")
@app.post("/send-email/" )
async def schedule_email (background_tasks : BackgroundTasks, email: str):
background_tasks .add_task(send_email, email, "Welcome!")
return {"message": "Email scheduled" }
Benefits
Decouples heavy tasks from HTTP requests
Improves API responsiveness
Best Practices for Async Programming
Avoid Blocking Code Replace sync libraries with async alternatives
Monitor Performance Use tools like Prometheus or New Relic
Test Thoroughly Simulate load to identify bottlenecks in async
execution
Use Middleware Async middleware for logging or preprocessing
@app.middleware("http")
async def log_requests(request, call_next):
response = await call_next(request)
print(f"Request: {request.url}")
return response
Testing Async Endpoints
Why Test Async APIs?
Ensure endpoints work as expected under various scenarios
Validate asynchronous behavior and performance
FastAPI’s Test Client
Built on httpx for async testing
Provides an easy way to test endpoints without a running server
Test Result
Conclusion
Scalability: Asynchronous programming in FastAPI handles more requests efficiently,
making your APIs ready for growth.
Responsiveness: Keeps your applications fast and user-friendly, even under heavy
workloads.
Efficiency: Optimizes resource usage by avoiding idle waits during I/O operations.
Best Practices: Use async libraries, monitor performance, and thoroughly test your code for
reliability and success.

More Related Content

PDF
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
PDF
How Optimizely Scaled its REST API with asyncio
PDF
A Beginners Guide to Building MicroServices with FastAPI
PDF
Enterprise-Ready FastAPI: Beyond the Basics
PPTX
Web Dev 21-01-2024.pptx
PDF
AsyncIO in Python (Guide and Example).pdf
PDF
AsyncAPI specification
PPTX
Async programming and python
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
How Optimizely Scaled its REST API with asyncio
A Beginners Guide to Building MicroServices with FastAPI
Enterprise-Ready FastAPI: Beyond the Basics
Web Dev 21-01-2024.pptx
AsyncIO in Python (Guide and Example).pdf
AsyncAPI specification
Async programming and python

Similar to Boost Your API with Asynchronous Programming in FastAPI (20)

PPTX
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
PPTX
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
PDF
AsyncAPI and Springwolf: Automated documentation and more
PDF
Asynchronous Python at Kumparan
PDF
FastAPI - Rest Architecture - in english.pdf
PDF
A Comprehensive Guide to Using Python for Backend API Development
PPTX
Synchronous vs Asynchronous Programming
PDF
PPTX
Asynchronous programming with django
PDF
5 Things about fastAPI I wish we had known beforehand
PPTX
Asynchronous Python with Twisted
PDF
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
PDF
PyCon Poland 2016: Maintaining a high load Python project: typical mistakes
PDF
APIdays Paris 2019 Backend is the new frontend by Antoine Cheron
PPTX
Why Your Business Should Leverage Python App Development in 2023.pptx
PPTX
Essential API Facade Patterns: Synchronous to Asynchronous Conversion (Episod...
PDF
Building Web APIs that Scale
PDF
Node js vs Django: Which is Better Backend Framework.pdf
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
AsyncAPI and Springwolf: Automated documentation and more
Asynchronous Python at Kumparan
FastAPI - Rest Architecture - in english.pdf
A Comprehensive Guide to Using Python for Backend API Development
Synchronous vs Asynchronous Programming
Asynchronous programming with django
5 Things about fastAPI I wish we had known beforehand
Asynchronous Python with Twisted
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
PyCon Poland 2016: Maintaining a high load Python project: typical mistakes
APIdays Paris 2019 Backend is the new frontend by Antoine Cheron
Why Your Business Should Leverage Python App Development in 2023.pptx
Essential API Facade Patterns: Synchronous to Asynchronous Conversion (Episod...
Building Web APIs that Scale
Node js vs Django: Which is Better Backend Framework.pdf
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Ad

More from techprane (16)

PDF
REDIS + FastAPI: Implementing a Rate Limiter
PDF
Performance Optimization MongoDB: Compound Indexes
PPTX
SSO with Social Login Integration & FastAPI Simplified
PDF
A Beginner's Guide to Tortoise ORM and PostgreSQL
PDF
Top 10 Network Troubleshooting Commands.pdf
PPTX
Using jq to Process and Query MongoDB Logs
PPTX
How to Integrate PostgreSQL with Prometheus
PPTX
10 Basic Git Commands to Get You Started
PPTX
Top Linux 10 Commands for Windows Admins
PPTX
Implementing full text search with Apache Solr
PPTX
How to Overcome Doubts as a New Developer(Imposter Syndrome)
PPTX
How to Use JSONB in PostgreSQL for Product Attributes Storage
PDF
Implementing Schema Validation in MongoDB with Pydantic
PPTX
Storing Large Image Files in MongoDB Using GRIDFS
PPTX
Open Source Mapping with Python, and MongoDB
PPTX
Learning MongoDB Aggregations in 10 Minutes
REDIS + FastAPI: Implementing a Rate Limiter
Performance Optimization MongoDB: Compound Indexes
SSO with Social Login Integration & FastAPI Simplified
A Beginner's Guide to Tortoise ORM and PostgreSQL
Top 10 Network Troubleshooting Commands.pdf
Using jq to Process and Query MongoDB Logs
How to Integrate PostgreSQL with Prometheus
10 Basic Git Commands to Get You Started
Top Linux 10 Commands for Windows Admins
Implementing full text search with Apache Solr
How to Overcome Doubts as a New Developer(Imposter Syndrome)
How to Use JSONB in PostgreSQL for Product Attributes Storage
Implementing Schema Validation in MongoDB with Pydantic
Storing Large Image Files in MongoDB Using GRIDFS
Open Source Mapping with Python, and MongoDB
Learning MongoDB Aggregations in 10 Minutes
Ad

Recently uploaded (20)

PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
Teaching material agriculture food technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Unlocking AI with Model Context Protocol (MCP)
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
Spectral efficient network and resource selection model in 5G networks
Teaching material agriculture food technology
20250228 LYD VKU AI Blended-Learning.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Approach and Philosophy of On baking technology
Unlocking AI with Model Context Protocol (MCP)

Boost Your API with Asynchronous Programming in FastAPI

  • 1. Samuel Folasayo Boost Your API with Asynchronous Programming in FastAPI Implementing Async Programming for High-Performance APIs Joe Nyirenda
  • 2. Learning Objectives ● Understand the fundamentals of asynchronous programming ● Learn how to set up a FastAPI environment for async development ● Use async libraries for HTTP requests, database operations, and file handling ● Implement background tasks to enhance API responsiveness ● Write and test async endpoints effectively using FastAPI's test client ● Apply best practices to avoid common pitfalls in async programming
  • 3. Overview What is Asynchronous Programming? A programming model that allows operations to execute non-blockingly Ideal for I/O-bound tasks like HTTP requests, database queries, and file operations
  • 4. Synchronous vs Asynchronous Programming Synchronous: One task at a time; blocks the next task Asynchronous: Tasks can overlap, improves scalability and resource usage
  • 5. Why FastAPI? Built on Starlette and Pydantic Natively supports async/await syntax for optimal performance Designed for high-concurrency and minimal latency
  • 6. Setting Up FastAPI for Async Development Environment Setup Install FastAPI for async web serving: pip install “fastapi[standard]” Writing an Async Endpoint Basic example: from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} Key Points: Use async def for non-blocking functions Use await when calling async libraries
  • 7. Asynchronous Libraries for FastAPI Why Async Libraries Matter Using synchronous libraries in an async app blocks the event loop Leads to poor scalability and performance Async HTTP Requests Use httpx instead of requests: import httpx @app.get("/external-api" ) async def call_external_api (): async with httpx.AsyncClient() as client: response = await client.get("https://example.com/api" ) return response.json()
  • 8. Asynchronous Libraries for FastAPI Async Database Operations Use async ORMs like Tortoise ORM or SQLAlchemy 1.4: from tortoise import Tortoise await Tortoise.init(...) results = await MyModel.filter( name="example") Async File Operations Use aiofiles for non-blocking file I/O: import aiofiles async with aiofiles.open("file.txt", mode="r") as file: content = await file.read()
  • 9. Enhancing Performance with Async Background Tasks Background Tasks in FastAPI Ideal for long-running tasks (e.g., sending emails, processing data) Example: Sending an Email from fastapi import BackgroundTasks # Placeholder function def send_email(email: str, message: str): print(f"Sending email to {email}") @app.post("/send-email/" ) async def schedule_email (background_tasks : BackgroundTasks, email: str): background_tasks .add_task(send_email, email, "Welcome!") return {"message": "Email scheduled" } Benefits Decouples heavy tasks from HTTP requests Improves API responsiveness
  • 10. Best Practices for Async Programming Avoid Blocking Code Replace sync libraries with async alternatives Monitor Performance Use tools like Prometheus or New Relic Test Thoroughly Simulate load to identify bottlenecks in async execution Use Middleware Async middleware for logging or preprocessing @app.middleware("http") async def log_requests(request, call_next): response = await call_next(request) print(f"Request: {request.url}") return response
  • 11. Testing Async Endpoints Why Test Async APIs? Ensure endpoints work as expected under various scenarios Validate asynchronous behavior and performance FastAPI’s Test Client Built on httpx for async testing Provides an easy way to test endpoints without a running server
  • 13. Conclusion Scalability: Asynchronous programming in FastAPI handles more requests efficiently, making your APIs ready for growth. Responsiveness: Keeps your applications fast and user-friendly, even under heavy workloads. Efficiency: Optimizes resource usage by avoiding idle waits during I/O operations. Best Practices: Use async libraries, monitor performance, and thoroughly test your code for reliability and success.