In This Project We learn how to start with FastAPI
FastAPI is an Open Source Library in Python, used to create Servers just like Django & Flask, with more use case and for API deployment (mostly for ML & AI integrations)
To Start with you'll need 3 Libraries named as
- FastAPI
- Uvicorn
- Starlette
The Following command is used to download the required libraries
pip install fastapi
pip install uvicorn
pip install statlette
We also provide
requirement.txtwith this project repo you can also download and install all dependencies form this file.Commands to install dependencies from
requirement.txtis given billow
pip install -r requirement.txt
Now you are ready to code
Create a Directory named
fastapi[You can use any made up names]Create a file named
main.pyCopy and Paste the following code in to that file
import uvicorn
if __name__ == '__main__':
uvicorn.run("app.app:app", port=8001, reload=True)
Create another Directory in the main Directory named
appCreate two files named
__init__.pyandapp.pyCopy and Paste the following code in to the
app.pyfile
from fastapi import FastAPI
app = FastAPI()
@app.get("/", tags=['ROOT'])
async def root() -> dict:
return {'Hello': 'FastAPI'}
use of
asyncbefore defining the function is good practice for FastAPI, and the function returns theDictionarywhich is denoted asdict
Your Server is ready to fire.
Open the terminal and run this command
python main.py
You'll see the server is running like this fashion
(venv) PS C:\Users\...\fastapi> python main.py
INFO: Will watch for changes in these directories: ['C:\\Users\\...\\fastapi']
INFO: Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)
INFO: Started reloader process [7936] using StatReload
INFO: Started server process [8788]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:54208 - "GET / HTTP/1.1" 200 OK
Now open this link http://127.0.0.1:8001 in to your Browser.
This is how it looks like
Now got to this Link http://127.0.0.1:8001/docs . The page will look like this
Now Click on
Try it outand then Click onExecuteThen you'll see some message and a link has been displayed billow the
ExecuteButton like thisNow Copy the command from the
Curl
curl -X 'GET' \
'http://127.0.0.1:8001/' \
-H 'accept: application/json'
And Paste it on
GitBashTerminal. You can see the message on the terminal like thisThis is basic app by FastAPI You can also
- Create
- Read
- Update
- Delete
by using
FastAPIAnd the method we use to do for that are
- Get
- Post
- Put
- Delete
Let's see how the
Getmethod is looks like
Create another function and do the same for the Basic App Creation just like this
# Get Method to create a post
@app.get("/val", tags=['VAL'])
async def val() -> dict:
return {'data': values}
values = [
{
'id': '1',
'name': 'APPARKY'
},
{
'id': '2',
'name': 'Apparium'
}
]
This is similar to Basic App, Except we return variable named
valueand pass a dictionary in it. This is How the OutPut Looks like for Get MethodNow got to this Link http://127.0.0.1:8001/docs . The page will look like this
Now Click on
Try it outand then Click onExecuteNow Copy the command from the
Curl
curl -X 'GET' \
'http://127.0.0.1:8001/val' \
-H 'accept: application/json'
And Paste it on
GitBashTerminal. You can see the message on the terminal like this
Create another function for
Postjust like this
@app.post("/val", tags=['VAL'])
async def post_val(val: dict) -> dict:
values.append(val)
return {
'data': 'Data Has been added Successfully'
}
In this function a parameter has been assigned in a form of dictionary, by which we can save data.
Let's see how dose it looks like
Now expand it and click on
Try it outand then Paste data on Request Body section like this
{
"id": "3",
"name": "Tame The Codes"
}
Click on Execute. This is how it looks like..
To check if the was added or not, follow the Get Method to see the data..
Here you can see the Data has been added.
You can also use
CurlTo add Data. We already discuss aboutCurl, this is the code
curl -X 'POST' \
'http://127.0.0.1:8001/val' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"id": "3",
"name": "Tame The Codes"
}'
This is how it looks like..
You can see the on this link http://localhost:8001/val . And this is how it looks like..
Put Method is used to Update the Stored Date. Create a Function on
app.pyfor that like this :
@app.put("/val{_id}", tags=['VAL'])
async def put_val(_id: int, body: dict) -> dict:
for val in values:
if int(val['id']) == _id:
print(val['id'])
print(_id)
val['name'] = body['name']
return {
'data': f'Values with id {_id} has been updated'
}
return {
'data': f'id {_id} not Found'
}
This is how the web page looks like :
Again follow the same method Click to
Try it outgive theidon_idsection and Click onExecute. This is how it looks like.This is the
Curlfor the sameThis is how
Curllooks like onGitBashNow click on this link http://localhost:8001/val . Check the value here .
As the name says, this will delete the data. Code for that are given billow
@app.delete("/val{_id}", tags=['VAL'])
async def delete_val(_id: int) -> dict:
for val in values:
if int(val['id']) == _id:
values.remove(val)
return {
"data": f"id {_id} has been updated"
}
return {
"data": f"id {_id} not Found"
}
This is how it looks like ...
To Delete data follow the same ..
CurlCode to Delete data ..We are done.
Thanks and regards Apparky
To get more interesting projects follow our GitHub page at Here
To get more interesting projects follow our Bitbucket page at Here