Fast Api [part 1 ]

Hello there, today we’ll look at how to use Fast APi to develop a rest API. It allows you to quickly construct APIs with minimal code.

Prerequisite to follow along

🎯 Python installed
🎯 Pipenv Virtual Environment
🎯 Vscode

Install pipenv

pi…


This content originally appeared on DEV Community and was authored by Abayomi Ogunnusi

Hello there, today we'll look at how to use Fast APi to develop a rest API. It allows you to quickly construct APIs with minimal code.
fast

Prerequisite to follow along

🎯 Python installed
🎯 Pipenv Virtual Environment
🎯 Vscode

Install pipenv

pip install --user pipenv

Following along requires the following prerequisites:

Install fastapi
pipenv install fastapi
This creates Pipfile and Pipfile.lock files in your project directory. Think of these like our package.json and package.lock.json files in Nodejs. The pipfile holds our project dependencies.

Image description

Image description

We need uvicorn to start our server. source
pipenv install uvicorn[standard]

Basic app setup

Now lets build a server.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

The above is the most basic version of our restapi.
We now have a problem because we use vscode and our Python interpreter cannot be found.

Fixing import "fastapi" could not be resolved

1) Press Ctrl + Shift + P on your VsCode

Image description

2) Select the python interpreter that matches your project name
Image description

We no longer have any warnings.
Then we launch our app by issuing the following command.
uvicorn main:app --reload

Image description

Testing our api

Lets visit our browser to at the host and port given to us when we ran the uvicorn command. Open your browser at http://127.0.0.1:8000

Image description

We got our JSON response.

Let's create another endpoint that outputs a list of dictionary, like an array of object in Javascript.

Image description

Now lets visit our browser http://127.0.0.1:8000/persons

Image description

The beauty of FastApi is that it comes preloaded with a documentation engine called Swagger.

We go to get the documentation for the two endpoints we mentioned earlier by visiting http://127.0.0.1:8000/docs

Image description

Image description

Next, we create a post request using BaseModel from pydantic

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}



@app.get("/persons")
async def persons():
    return {"data": [
                        {"name": "John", "age": 30, "tall": True},
                        {"name": "Doe", "age": 25}
                    ]}

class Person(BaseModel):
    name: str
    age: int | None = None
    tall: bool = False

@app.post("/persons")
async def create_person(person: Person):
    return {"data": person} 

Now let's test our create_person endpoint using the swagger docs
Image description

When you click on execute you get:
Image description

Let's perform methods on our pydantic model.
  • change our name to uppercase
  • use string formatting to output our result
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


class Person(BaseModel):
    name: str
    age: int | None = None
    tall: bool = False

@app.post("/persons")
async def create_person(person: Person):
    return {"data": f"my name is {person.name.upper()} and i am {person.age} years old"}

Result:
Image description

Conclusion

In a matter of minutes, we learned how to create a restapi using this modern Python framework, and we explored the swagger documentation that comes pre-installed with fast api.
In the following lesson, we'll look at how to create full CRUD functionality against a sqlalchemy database, as well as error handling and status code.

I hope you found this post useful; thank you for taking the time to read it.


This content originally appeared on DEV Community and was authored by Abayomi Ogunnusi


Print Share Comment Cite Upload Translate Updates
APA

Abayomi Ogunnusi | Sciencx (2022-03-31T15:46:36+00:00) Fast Api [part 1 ]. Retrieved from https://www.scien.cx/2022/03/31/fast-api-part-1/

MLA
" » Fast Api [part 1 ]." Abayomi Ogunnusi | Sciencx - Thursday March 31, 2022, https://www.scien.cx/2022/03/31/fast-api-part-1/
HARVARD
Abayomi Ogunnusi | Sciencx Thursday March 31, 2022 » Fast Api [part 1 ]., viewed ,<https://www.scien.cx/2022/03/31/fast-api-part-1/>
VANCOUVER
Abayomi Ogunnusi | Sciencx - » Fast Api [part 1 ]. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/31/fast-api-part-1/
CHICAGO
" » Fast Api [part 1 ]." Abayomi Ogunnusi | Sciencx - Accessed . https://www.scien.cx/2022/03/31/fast-api-part-1/
IEEE
" » Fast Api [part 1 ]." Abayomi Ogunnusi | Sciencx [Online]. Available: https://www.scien.cx/2022/03/31/fast-api-part-1/. [Accessed: ]
rf:citation
» Fast Api [part 1 ] | Abayomi Ogunnusi | Sciencx | https://www.scien.cx/2022/03/31/fast-api-part-1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.