FastAPI application creation code analysis | HTTP GET request demo code
FastAPI application code
Analyzing GET HTTP request Method:
sample code: It is for GET request code to read data from API endpoint.
book.py
from fastapi import FastAPI # including package of FastAPI and all dependencies.
app = FastAPI() #Allows to use all dependencies which come with FastAPI package with the help of variable names app which stand for application.
@app.get("/api-endpoint") #path where we will have the function async def first_api. So it is the route to invoke this function. This will be the path which user need to use in http url to call the method for activity.
async def first_api():
return {'message': 'Hello Puneet!'}
Note:
async - it is a python function and not needed in FastAPI as FastAPI implement and use it in background.
As we need to create a read method or GET https request method from API endpoint side hence we need to add this async def first_api() method to this GET https request method.
@app.get("/api-endpoint") - it is a decorator.
We need to open our terminal and need to run below command to execute the API.
uvicorn books:app --reload
Here books.py is the file which need to be run and app is the variable which will ask FastAPI to run and reload is the command to update the code in browser and run it.
Code for reading the books entries:
@app.get("/listOfBooks")
async def read_all_books():
return BOOKS
It will return the list of the books which we have in specified URL.
Application run Demo:
Result of the application when giving right URL for result.
Commands to run application from terminal in local system is:
- uvicorn books:app --reload
- fastapi run book.py -> It will run the code in production mode of FastAPI cli.
- fastapi dev book.py -> It will run the code in developer mode of FastAPI cli.
- to run fastapi command need to install fastapi[standard]
- command is : pip install "fastapi[standard]"




Comments
Post a Comment