DEV Community

Cover image for FastApi Example
Ronny Medina
Ronny Medina

Posted on

FastApi Example

Video en español.

Hello everyone, in this post I'm going to show you a small example with FastApi.

Well, to use FastApi, we need to install some dependencies such as:

  • pip install fastapi
  • pip install uvicorn[standard]

Or we can create a requirements file. requirements.txt.

fastapi==0.65.2
uvicorn==0.14.0
Enter fullscreen mode Exit fullscreen mode

And then run the following command pip install -r requirements.txt.

The next step is to create a main file main.py and put the following content inside.

from fastapi import FastAPI

app = FastAPI()


@app.get('/')
def root():
    return 'ok'


@app.get('/item/{id}')
def read_item(id: int):
    return id
Enter fullscreen mode Exit fullscreen mode

Now we can run the following command uvicorn main:app --reload.

We can check the urls in our browser http://localhost:8000/ and http://localhost:8000/item/1.

By default, FastApi has swagger included. We can check this url in your browser http://localhost:8000/docs. Another system is also integrated to document our api. You can visit http://localhost:8000/redoc.

The documentation of our api is automatic. This happens when we write the typing of our code. If you change this line def read_item(id: int) to def read_item(id: str) this updates our documentation.

To keep things in order we can create folder app and inside the following structure.

Example structure

And inside the schemas we are going to create two files. A item.py this file is to save the validations of this resource.

from typing import Optional
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str =  Field(None, title='Example title...', min_length=3, max_length=10)
    price: float = Field(None, title='Price 300')
    is_offer: Optional[bool] = Field(False, title='Is offer')

Enter fullscreen mode Exit fullscreen mode

You can visit the official page for more information pydantic-docs. Then we are going to create a __init__.py to export this validation.


from .item import Item as ItemSchema
Enter fullscreen mode Exit fullscreen mode

Now we're going to create router file (router.py).


from typing import List
from fastapi import APIRouter

from .schemas import ItemSchema


router = APIRouter()

@router.get('/items', tags=['items'], response_model=List[ItemSchema])
def list_item() -> List[ItemSchema]:
    return []


@router.get('/items/{id}', tags=['items'])
def read_item(id: int) -> int:
    return id


@router.post('/items', tags=['items'], response_model=ItemSchema)
def create_item(data: ItemSchema):
    return data
Enter fullscreen mode Exit fullscreen mode

Now we need to export this router to use it. You can create another __init__.py at the same level as the item folder.


from .router import router as item_router
Enter fullscreen mode Exit fullscreen mode

And finally we need to update our main file.


from fastapi import FastAPI

from .items import item_router

app = FastAPI()

app.include_router(item_router)


@app.get('/')
def root():
    return 'ok'
Enter fullscreen mode Exit fullscreen mode

To run our api we can execute this command uvicorn app.main:app --reload

Now we split our application and update the documentation.

How does validation work in FastApi?

This runs as a middleware if the data is invalid the return statement is never executed. You can try to pass invalid data to this API.


@router.post('/items', tags=['items'], response_model=ItemSchema)
def create_item(data: ItemSchema):
    return data
Enter fullscreen mode Exit fullscreen mode

Request example

Alt Text

Well this was a small example with FastApi. I Hope this was helpful to you.

Top comments (3)

Collapse
 
ionfreeman profile image
Ion Freeman

Hey, Ronny! I'm wondering if you know why the documentation has you do
from .router import router as item_router
instead of just
item_router = APIRouter()

Collapse
 
anson2416 profile image
anson2416

Hi Ronny, thanks for the detail post.
Can you share more details on the usage of tags=['items'] ? Thank you.

Collapse
 
sm0ke profile image
Sm0ke

Nice ..