FastApi Example
Tags: beginners
Published: 2021-06-14 02:35:28

Video en español.
{% youtube oMVf_ph2tGs %}


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`.

```txt
fastapi==0.65.2
uvicorn==0.14.0
```

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.

```python
from fastapi import FastAPI

app = FastAPI()


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


@app.get('/item/{id}')
def read_item(id: int):
    return id
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jvf9d78pnj1p4u8q62fr.png)

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


```python
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')

```

You can visit the official page for more information [pydantic-docs](https://pydantic-docs.helpmanual.io/). Then we are going to create a `__init__.py` to export this validation.

```python

from .item import Item as ItemSchema
```
Now we're going to create router file (`router.py`).


```python

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
``` 

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

```python

from .router import router as item_router
```

And finally we need to update our main file.

```python

from fastapi import FastAPI

from .items import item_router

app = FastAPI()

app.include_router(item_router)


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

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.

```python

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

![Request example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6skpcinyco4fzkccpc2q.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lupfqxldephl56weo4z.png)

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