How to create post and get api in fastapi python
Get Function:
- 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:
![](https://blogshub.co.in/wp-content/uploads/2023/12/image-15-1024x580.png)
POST Function:
- 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:
![](https://blogshub.co.in/wp-content/uploads/2023/12/image-14-1024x501.png)
🙂 Keep Learning