Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

FastAPI

From Wikipedia, the free encyclopedia
Web framework for Python
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This articlecontainspromotional content. Please helpimprove it by removingpromotional language and inappropriateexternal links, and by adding encyclopedic text written from aneutral point of view.(February 2022) (Learn how and when to remove this message)
This articlerelies excessively onreferences toprimary sources. Please improve this article by addingsecondary or tertiary sources.
Find sources: "FastAPI" – news ·newspapers ·books ·scholar ·JSTOR
(February 2022) (Learn how and when to remove this message)
(Learn how and when to remove this message)
FastAPI
DeveloperSebastián Ramírez
Initial releaseDecember 5, 2018; 6 years ago (2018-12-05)[1]
Stable release
0.120.0[2] Edit this on Wikidata / 23 October 2025; 4 days ago (23 October 2025)
Repositorygithub.com/tiangolo/fastapi
Written inPython
TypeWeb framework
LicenseMIT
Websitefastapi.tiangolo.com

FastAPI is a high-performanceweb framework for buildingHTTP-based serviceAPIs inPython 3.8+.[3] It uses Pydantic and type hints tovalidate,serialize and deserialize data. FastAPI also automatically generatesOpenAPI documentation for APIs built with it.[4] It was first released in 2018.

Components

[edit]

Pydantic

[edit]

Pydantic is a data validation library for Python. While writing code in anIDE, Pydantic provides type hints based on annotations.[5] FastAPI extensively utilizes Pydantic models for data validation, serialization, and automatic API documentation. These models are using standard Python type hints, providing a declarative way to specify the structure and types of data for incoming requests (e.g., HTTP bodies) and outgoing responses.[6]

fromfastapiimportFastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strprice:floatis_offer:bool|None=None@app.post("/items/")defcreate_item(item:Item):# The 'item' object is already validated and typedreturn{"message":"Item received","item_name":item.name}

Starlette

[edit]

Starlette is a lightweightASGI framework/toolkit, to support async functionality in Python.[7]

Uvicorn

[edit]

Uvicorn is a minimal low-level server/application web server for async frameworks, following theASGI 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.[8]

OpenAPI integration

[edit]

FastAPI automatically generatesOpenAPI documentation for APIs. This documentation includes bothSwagger UI andReDoc, which provide interactive API documentation that you can use to explore and test your endpoints in real time. This is particularly useful for developing, testing, and sharing APIs with other developers or users. Swagger UI is accessible by default at/docs and ReDoc at/redoc route.[9]

Features

[edit]

Asynchronous operations

[edit]

FastAPI's architecture inherently supportsasynchronous programming. This design allows thesingle-threadedevent 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, seeasync/await pattern.

Dependency injection

[edit]

FastAPI incorporates aDependency 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.[10]

fromfastapiimportDepends,HTTPException,statusfromdbimportDbSession# --- Dependency for Database Session ---defget_db():db=DbSession()try:yielddbfinally:db.close()@app.post("/items/",status_code=status.HTTP_201_CREATED)defcreate_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}")defread_item(item_id:int,db:DbSession=Depends(get_db)):item=db.query(Item).filter(Item.id==item_id).first()ifitemisNone:raiseHTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Item not found")returnitem

WebSockets support

[edit]

WebSockets 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.[11]

# You must have 'websockets' package installedfromfastapiimportWebSocket@app.websocket("/ws")asyncdefwebsocket_endpoint(websocket:WebSocket):awaitwebsocket.accept()whileTrue:data=awaitwebsocket.receive_text()awaitwebsocket.send_text(f"Message text was:{data}")

Background tasks

[edit]

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.[12]

importtimeimportshutilfromfastapiimportBackgroundTasks,UploadFile,Filefromutilsimportgenerate_thumbnail@app.post("/upload-image/")asyncdefupload_image(image:UploadFile=File(...),background_tasks:BackgroundTasks):file_location=f"uploaded_images/{image.filename}"# Save uploaded imagewithopen(image_path,"wb")asf:contents=awaitfile.read()f.write(contents)# Add thumbnail generation as a background tasktasks.add_task(generate_thumbnail,file_location,"200x200")return{"message":f"Image '{image.filename}' uploaded. Thumbnail generation started in background."}

Example

[edit]

The following code shows a simple web application that displays "Hello, World!" when visited:

# Import FastAPI class from the fastapi packagefromfastapiimportFastAPI# Create an instance of the FastAPI appapp=FastAPI()# Define a GET route for the root URL ("/")@app.get("/")asyncdefread_root()->str:# Return a plain text responsereturn"Hello, World!"

See also

[edit]

External links

[edit]

References

[edit]
  1. ^"fastapi repo".GitHub. 2018-12-05.
  2. ^"Release 0.120.0". 23 October 2025. Retrieved25 October 2025.
  3. ^"FastAPI".fastapi.tiangolo.com. Retrieved2024-04-10.
  4. ^Lubanovic, Bill (2019-11-06).Introducing Python: Modern Computing in Simple Packages (2nd ed.). O'Reilly Media, Inc. pp. 397, 418.ISBN 9781492051367.
  5. ^"Why use Pydantic - Pydantic".docs.pydantic.dev. Retrieved2023-09-21.
  6. ^"Request Body - FastAPI".fastapi.tiangolo.com. Retrieved2025-06-30.
  7. ^"Starlette".www.starlette.io. Retrieved2023-09-21.
  8. ^"Restarting 'uvicorn' Workers with the 'SIGHUP' Signal".bugfactory.io. Retrieved2024-06-17.
  9. ^https://fastapi.tiangolo.com/reference/openapi/docs/
  10. ^"Dependencies". Retrieved30 June 2025.
  11. ^"WebSockets - FastAPI".fastapi.tiangolo.com. Retrieved2025-06-30.
  12. ^"Background Tasks - FastAPI".fastapi.tiangolo.com. Retrieved2025-06-30.
.NET
C++
ColdFusion
Common Lisp
Haskell
Java
JavaScript
Perl
PHP
Python
Ruby
Rust
Scala
Smalltalk
Other languages
Retrieved from "https://en.wikipedia.org/w/index.php?title=FastAPI&oldid=1311338147"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp