Content deleted Content added
m Added the `async` keyword to the function which more closely aligns with the example code in the official FastAPI documentation. |
m →Example |
||
(6 intermediate revisions by 5 users not shown) | |||
Line 24:
=== Pydantic ===
Pydantic is a data validation library for Python. While writing code in an [[Integrated development environment|IDE]], Pydantic provides type hints
<syntaxhighlight lang="python">
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool | None = None
@app.post("/items/")
def create_item(item: Item):
# The 'item' object is already validated and typed
return {"message": "Item received", "item_name": item.name}
</syntaxhighlight>
=== Starlette ===
Line 32 ⟶ 49:
Uvicorn is a minimal low-level server/application web server for async frameworks, following the [https://asgi.readthedocs.io/en/latest/ ASGI specification]. Technically, it implements a multi-process model with one main process, which is responsible for managing a pool of worker processes and distributing incoming HTTP requests to them. The number of worker processes is pre-configured, but can also be adjusted up or down at runtime.<ref>{{Cite web |title=Restarting 'uvicorn' Workers with the 'SIGHUP' Signal |url=https://bugfactory.io/articles/restarting-uvicorn-workers-with-the-sighup-signal/ |access-date=2024-06-17 |website=bugfactory.io}}</ref>
=== OpenAPI
FastAPI automatically generates [[OpenAPI Specification|OpenAPI]] documentation for
== Features ==
=== Asynchronous operations ===
FastAPI's architecture inherently supports '''asynchronous programming'''. This design allows the [[Global interpreter lock|single-threaded]] [[event loop]] to handle a large number of concurrent requests efficiently, particularly when dealing with I/O-bound operations like database queries or external API calls. For reference, see [[Async/await|async/await pattern]].
=== Dependency injection ===
FastAPI incorporates a [[Dependency injection|Dependency Injection (DI)]] system to manage and provide services to HTTP endpoints. This mechanism allows developers to declare components such as database sessions or authentication logic as function parameters. FastAPI automatically resolves these dependencies for each request, injecting the necessary instances.<ref>{{cite web |title=Dependencies |url=https://fastapi.tiangolo.com/tutorial/dependencies/#dependencies |access-date=30 June 2025}}</ref>
<syntaxhighlight lang="python">
from fastapi import Depends, HTTPException, status
from db import DbSession
# --- Dependency for Database Session ---
def get_db():
db = DbSession()
try:
yield db
finally:
db.close()
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(name: str, description: str, db: DbSession = Depends(get_db)):
new_item = Item(name=name, description=description)
db.add(new_item)
db.commit()
db.refresh(new_item)
return {"message": "Item created successfully!", "item": new_item}
@app.get("/items/{item_id}")
def read_item(item_id: int, db: DbSession = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
return item
</syntaxhighlight>
=== WebSockets support ===
[[WebSocket]]s allow full-duplex communication between a client and the server. This capability is fundamental for applications requiring continuous data exchange, such as instant messaging platforms, live data dashboards, or multiplayer online games. FastAPI leverages the underlying Starlette implementation, allowing for efficient management of connections and message handling.<ref>{{Cite web |title=WebSockets - FastAPI |url=https://fastapi.tiangolo.com/advanced/websockets/ |access-date=2025-06-30 |website=fastapi.tiangolo.com |language=en}}</ref>
<syntaxhighlight lang="python">
# You must have 'websockets' package installed
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
</syntaxhighlight>
=== Background tasks ===
FastAPI enables the execution of background tasks after an HTTP response has been sent to the client. This allows the API to immediately respond to user requests while simultaneously processing non-critical or time-consuming operations in the background. Typical applications include sending email notifications, updating caches, or performing data post-processing.<ref>{{Cite web |title=Background Tasks - FastAPI |url=https://fastapi.tiangolo.com/tutorial/background-tasks/ |access-date=2025-06-30 |website=fastapi.tiangolo.com |language=en}}</ref>
<syntaxhighlight lang="python">import time
import shutil
from fastapi import BackgroundTasks, UploadFile, File
from utils import generate_thumbnail
@app.post("/upload-image/")
async def upload_image(
image: UploadFile = File(...),
background_tasks: BackgroundTasks
):
file_location = f"uploaded_images/{image.filename}"
# Save uploaded image
with open(image_path, "wb") as f:
contents = await file.read()
f.write(contents)
# Add thumbnail generation as a background task
tasks.add_task(generate_thumbnail, file_location, "200x200")
return {"message": f"Image '{image.filename}' uploaded. Thumbnail generation started in background."}
</syntaxhighlight>
== Example ==
The following code shows a simple web application that displays "[["Hello, World!" program|Hello, World!]]
<syntaxhighlight lang="python
# Import FastAPI class from the fastapi package
from fastapi import FastAPI
# Create an instance of the FastAPI app
app = FastAPI()
# Define a GET route for the root URL ("/")
@app.get("/")
async def read_root() -> str:
# Return a plain text response
return "Hello, World!"
</syntaxhighlight>
Line 73 ⟶ 172:
[[Category:Software using the MIT license]]
[[Category:Web frameworks]]
|