FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of Starlette for the web parts and Pydantic for the data parts. FastAPI is easy to use, fast, and highly efficient, making it a popular choice for building APIs.
In this tutorial, I will walk you through the process of setting up a simple API using FastAPI, defining routes, creating models, and running the server.
- Installation:
First, you need to install FastAPI and Uvicorn, which is a lightning-fast ASGI server. You can install them using pip:
pip install fastapi uvicorn
- Creating a FastAPI app:
Create a new Python file, for example,main.py
and import the necessary modules:
from fastapi import FastAPI
from pydantic import BaseModel
Next, create an instance of the FastAPI class:
app = FastAPI()
- Defining routes:
Now, let’s define a simple route that returns a JSON response. Define a function with the@app.get
decorator to specify the route path:
@app.get("/")
def read_root():
return {"message": "Hello World"}
- Request parameters:
You can also define routes with parameters by specifying them in the function:
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
- Creating models:
FastAPI uses Pydantic models for request and response data validation. Define a Pydantic model for the request body:
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
- Request body:
You can use the Pydantic model in a route to validate the request body:
@app.post("/items/")
def create_item(item: Item):
return item
- Running the server:
To start the server, use the Uvicorn command-line tool and pass it the name of the Python file:
uvicorn main:app --reload
This command will start the server on http://localhost:8000
. You can access the routes you defined in your browser or using tools like Postman.
That’s it! You have now successfully created a simple API using FastAPI. FastAPI provides many more features like dependency injection, security, and documentation generation that you can explore in the official documentation.
Скажите, стоит ли учить фастапи если я +- знаю фласк? Или это тоже самое?
А как выполнить функцию, в которой есть input? Интерпретатор останавливается)
Нихуя себе, они изобрели обрезаный Flask без встроенной защиты и ключа XD
А зачем?)
Почему это вьюха это ендпоинт что ваще значит аьюха
Вау, чел со скиллбокс курса
Выглядит проще чем с django
Больше видео про API!!!😅✅
Выглядит как flask)
Целый стрим😊