SlideShare a Scribd company logo
7
Most read
8
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

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

PPTX
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
PPTX
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
skpdbz
 
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
PDF
AsyncAPI and Springwolf: Automated documentation and more
RaphaelDeLio1
 
PDF
Asynchronous Python at Kumparan
Bayu Aldi Yansyah
 
PDF
FastAPI - Rest Architecture - in english.pdf
inigraha
 
PDF
A Comprehensive Guide to Using Python for Backend API Development
Shiv Technolabs Pvt. Ltd.
 
PPTX
Synchronous vs Asynchronous Programming
jeetendra mandal
 
PDF
Async.pdf
AhmedMaherAlmaqtari
 
PPTX
Asynchronous programming with django
bangaloredjangousergroup
 
PDF
5 Things about fastAPI I wish we had known beforehand
Alexander Hendorf
 
PPTX
Asynchronous Python with Twisted
Adam Englander
 
PDF
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Pôle Systematic Paris-Region
 
PDF
PyCon Poland 2016: Maintaining a high load Python project: typical mistakes
Viach Kakovskyi
 
PDF
APIdays Paris 2019 Backend is the new frontend by Antoine Cheron
apidays
 
PPTX
Why Your Business Should Leverage Python App Development in 2023.pptx
OnGraph Technologies Pvt. Ltd.
 
PPTX
Essential API Facade Patterns: Synchronous to Asynchronous Conversion (Episod...
Apigee | Google Cloud
 
PDF
Building Web APIs that Scale
Salesforce Developers
 
PDF
Node js vs Django: Which is Better Backend Framework.pdf
Lily Clark
 
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
skpdbz
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
AsyncAPI and Springwolf: Automated documentation and more
RaphaelDeLio1
 
Asynchronous Python at Kumparan
Bayu Aldi Yansyah
 
FastAPI - Rest Architecture - in english.pdf
inigraha
 
A Comprehensive Guide to Using Python for Backend API Development
Shiv Technolabs Pvt. Ltd.
 
Synchronous vs Asynchronous Programming
jeetendra mandal
 
Asynchronous programming with django
bangaloredjangousergroup
 
5 Things about fastAPI I wish we had known beforehand
Alexander Hendorf
 
Asynchronous Python with Twisted
Adam Englander
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Pôle Systematic Paris-Region
 
PyCon Poland 2016: Maintaining a high load Python project: typical mistakes
Viach Kakovskyi
 
APIdays Paris 2019 Backend is the new frontend by Antoine Cheron
apidays
 
Why Your Business Should Leverage Python App Development in 2023.pptx
OnGraph Technologies Pvt. Ltd.
 
Essential API Facade Patterns: Synchronous to Asynchronous Conversion (Episod...
Apigee | Google Cloud
 
Building Web APIs that Scale
Salesforce Developers
 
Node js vs Django: Which is Better Backend Framework.pdf
Lily Clark
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 

More from techprane (16)

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

Recently uploaded (20)

PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Ad

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.