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.
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.
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
2) Select the python interpreter that matches your project name
We no longer have any warnings.
Then we launch our app by issuing the following command.
uvicorn main:app --reload
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
We got our JSON response.
Let's create another endpoint that outputs a list of dictionary, like an array of object in Javascript.
Now lets visit our browser http://127.0.0.1:8000/persons
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
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
When you click on execute you get:
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"}
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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.