Using FastAPI in Python

Posted by


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.

  1. 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
  1. 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()
  1. 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"}
  1. 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}
  1. 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
  1. 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
  1. 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.

0 0 votes
Article Rating
10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@gggppp228
1 month ago

Скажите, стоит ли учить фастапи если я +- знаю фласк? Или это тоже самое?

@АлексейБазаров-и5л
1 month ago

А как выполнить функцию, в которой есть input? Интерпретатор останавливается)

@Anshegar
1 month ago

Нихуя себе, они изобрели обрезаный Flask без встроенной защиты и ключа XD

@ЮрийФильмов
1 month ago

А зачем?)

@rvnclaw9914
1 month ago

Почему это вьюха это ендпоинт что ваще значит аьюха

@h3try
1 month ago

Вау, чел со скиллбокс курса

@ГубкаБоб-р8ъ
1 month ago

Выглядит проще чем с django

@МатвейЕгоров-ь6г
1 month ago

Больше видео про API!!!😅✅

@CAHCrawlAdaptHide
1 month ago

Выглядит как flask)

@ruria_coda
1 month ago

Целый стрим😊