FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use, fast to develop with, and highly performant.
Here are some key features and advantages of FastAPI:
Key Features
- High Performance: FastAPI is one of the fastest Python frameworks available, on par with NodeJS and Go in terms of performance.
- Easy to Use: It provides an easy-to-use interface, reducing the complexity involved in creating API endpoints.
- Automatic Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc.
- Type Hints and Validation: It uses Python-type hints to perform data validation and serialization, ensuring type safety and reducing bugs.
- Dependency Injection: Built-in dependency injection system allows for a clean and maintainable codebase.
- Asynchronous Support: Full support for asynchronous programming, which helps in handling a large number of concurrent connections efficiently.
- Standards-Based: It is built on top of standard Python-type hints and the OpenAPI standard, ensuring compatibility and ease of integration with other tools and libraries.
Getting Started
To create a basic API with FastAPI, follow these steps:
1. Install FastAPI and an ASGI server (e.g., uvicorn):
pip install fastapi uvicorn
2. Create a basic FastAPI app:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
3. Run the application:
uvicorn main:app --reload
#Here, main refers to your Python file (e.g., main.py), and app is the FastAPI instance.
4. Open a Web Browser:
After starting your FastAPI app, open a web browser and navigate to http://127.0.0.1:8000/
.
Steps to Access the Documentation
To find the automatically generated API documentation for your FastAPI application, you can access the following URLs after running your FastAPI app.
1. Swagger UI: Provides an interactive API documentation interface.
- URL:
/docs
- Example:
http://127.0.0.1:8000/docs
2. ReDoc: An alternative interactive API documentation interface.
- URL:
/redoc
- Example:
http://127.0.0.1:8000/redoc
Customizing Documentation URLs
If you want to customize the paths for the documentation, you can do so by specifying the docs_url
and redoc_url
parameters when creating your FastAPI app instance:
from fastapi import FastAPI
app = FastAPI(
docs_url="/my-custom-docs",
redoc_url="/my-custom-redoc"
)
@app.get("/")
async def read_root():
return {"Hello": "World"}
In this example, the Swagger UI documentation would be available at http://127.0.0.1:8000/my-custom-docs
and the ReDoc documentation at http://127.0.0.1:8000/my-custom-redoc
. By default, FastAPI provides these automatically generated documentation interfaces, making it easy to test and interact with your API endpoints.