Python FastAPI Basic



FastAPI is a WebFramework, mainly for Python 

Why Fast API.

simplicity and its asynchronous in nature,

Asynchronous, in a Webpage, we are not waiting for one request to another request. 

Ex: in a restaurant, Cook will prepare food different items at the same time. 

He dont want to wait for the first item to be completed and prepare another one.

Installation:

its a python library so after installation, we can directly install it.

pip install fastapi & pip install uvicorn

try learning additionally about the uvicorn as well, so the installation & maintenance will be easy.

=======app.py========

# command to run: uvicorn app:app --reload --host 0.0.0.0 --port 8001

from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
    name: str
    age: int
    phone: int

app=FastAPI()

# http://localhost:8001/
@app.get("/") # defining @app is called as decorator.
def home():
    return {"message":"hello world!"}

# http://localhost:8001/home/
@app.get("/home")
def home1():
    return {"message":"hello world1!"}

# http://localhost:8001/item/1
@app.get("/item/{item_id}")
def item(item_id: int):
    return {"message ":" Hello ${item_id}", "item_id": item_id}

# http://localhost:8001/search?q=1&name=test
@app.get("/search")
def search(q: str=None, name: str=""):
    return {"query": q, "name": name}

# http://localhost:8001/items
# payload: {"name":"test", "age": 10}
@app.post("/items")
# def create(items: dict):
def create(items: Item): #data is pulled from Item class (Pydantic model ex.)
    return {"item": items}

# check the swagger docs in below url>
# http://localhost:8001/docs

==============

Command to run

uvicorn app:app --reload --host 0.0.0.0 --port 8001


url: https://<ipaddress/domain_name>:port/<functionA>

url params are like a methods.

check the below website for a sample rest API request.

JSONPlaceholder - Free Fake REST API

In this example 

https://jsonplaceholder.typicode.com/todos/1

/todo is consider like a function.

you can try hitting this API using bruno collection, just to check the request and response for this.

we can pass the parameters in two ways 

1) Path parameter (return based on the path params.)

2) Query parameter (mainly used to check condition and provide response)


Ex:

https://www.<hostname>.com/path_param?query_param_name=query_param_value&query_param_name=query_param_value

& is used as a separator in query parameter.

 you can validate all these thing using Bruno

if its a graphql then go for Insomnia tool.


In the above we have seen a basic example for FastAPI also basic example for Pydantic example.

Sample GET and POST method has been covered now.

Comments