How to create post and get api in fastapi python

Get Function:

  1. Import fastapi
from fastapi import FastAPI

2. Create instance of FastAPI

app = FastAAPI() 

3. Create URI using instance

@app.get("/") 

4. Create function

Async def functionname() 

5. Describe function

Return {“Message”: “Your Message Here”} 

6. Start your webserver

uvicorn main:app --reload

7. Call URL using browser or postman

http://127.0.0.1:8000/
from fastapi import FastAPI
from fastapi.params import Body

app = FastAPI()

@app.get("/")
async def root():
    return {"Message" : "fastAPI first programme"}

Run API in Postman:

POST Function:

  1. Create URI using instance

@app.post("/createpost")

2. Create Function

Async def functionname()

3. Describe Function

return {"Message": "Create Post Here"}

Example:

from fastapi import FastAPI
from fastapi.params import Body

app = FastAPI()


@app.post("/createpost")
def createPost(payLoad : dict = Body(...)):
    # print(payLoad)
    return {"New Post": f"title {payLoad['post_title']} Description {payLoad['post_description']}"}

Run API using Postman:

🙂 Keep Learning

Leave a Reply

Your email address will not be published. Required fields are marked *