Hello Learners…
Welcome to the blog…
Table Of Contents
- Introduction
- Sending POST Requests to Python FastAPI from Another Python Script
- Create A Simple FastAPI
- Request FastAPI From Another Python Script
- Summary
- References
Introduction
In this post, we implementing the process of Sending POST Requests to Python FastAPI from Another Python Script. It is very useful when we are working with Python APIs.
As developers, we often encounter many types of situations where we need to interact with various APIs to exchange data and perform specific actions
Python FastAPI, a modern and high-performance web framework, provides an excellent solution for building web APIs.
To learn more about FastAPI,
Sending POST Requests to Python FastAPI from Another Python Script
First, we have to create a simple FastAPI and then we call that FastAPI using Python script.
Create A Simple FastAPI
Here we are going to a simple FastAPI just for understanding but you can take any level based on your requirements.
To install the required libraries we use the ‘pip’ python package manager.
pip install uvicorn==0.23.1 fastapi==0.100.1 requests==2.31.0 urllib3==1.26.6
now we create a mainapp.py file and paste the below code into this file.
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/text")
def read_item(msg_text: str):
return {"response":"your text is "+ msg_text}
if __name__=='__main__':
uvicorn.run(app,port=8005)
And then run the file in the one terminal using the below command,
python3 mainapp.py
When we run the mainapp.py file we get the URL http://127.0.0.1:8005.
We use this URL for the POST request to this FastAPI.Keep it running…
Send A Post Request To FastAPI From Another Python Script
Now we are going to call a FastAPI from another Python script.
To do this we create a file call_api.py and paste the code below in this file.
import requests
# url = 'http://localhost:8005/text'
url = 'http://127.0.0.1:8005/text'
headers = {'accept': 'application/json'}
data = {'msg_text': 'Welcome to the galaxy of ai'}
response = requests.post(url, headers=headers, params=data)
print(response.status_code)
print(response.json())
Now we run the call_api.py file. and we can see the response.
python3 call_api.py
The response that we get by calling FastAPI is below.
NOTE: mainapp.py must be in running mode.
200 {'response': 'your text is Welcome to the galaxy of ai'}
Throughout the blog, we covered the fundamentals of Python FastAPI, an efficient web framework designed for high-performance API development
Summary
As you continue your journey with FastAPI, remember the potential this integration offers.
Full Code Download From GitHub: https://github.com/galaxyofai/fastapi_call_post_request
Happy Learning And Keep Learning…
Thank You…