Create API Tester using Python Requests Module
Last Updated :
15 Mar, 2023
Prerequisites: Python Requests module, API
In this article, we will discuss the work process of the Python Requests module by creating an API tester.
API stands for Application Programming Interface (main participant of all the interactivity). It is like a messenger that takes our requests to a system and returns a response back to us via seamless connectivity. We use APIs in many cases like to get data for a web application or to connect to a remote server that has data like weather that keeps changing or to enable two applications to exchange data among each other.
The requests library is one of an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response.
Step-by-step Approach:
- First, we choose input from the user what they want.
- Take an input URL.
If the user chooses GET Request.
- In getReq() function, make a GET Request using the Requests module and store the result.
- Format the result using the JSON module and return it.
If the user chooses Post Request.
- Take a dictionary data to send to the server.
- In postReq() function, make a POST Request with JSON data using the Request module and store the result.
- Format the result using the JSON module and return it.
Finally, print the returned result.
Below is the implementation based on the above approach:
Python3
import requests
import json
def getReq(url):
try :
res = requests.get(url)
return json.dumps(res.json(), indent = 4 )
except Exception as ee:
return f "Message : {ee}"
def postReq(url, data):
try :
res = requests.post(url, json = data)
return json.dumps(res.json(), indent = 4 )
except Exception as er:
return f "Message : {er}"
if __name__ = = '__main__' :
while True :
try :
choice = int ( input ( "1.Get Request\n2.Post Request\n3.Exit\nEnter Choice : " ))
if choice = = 1 :
url_inp = input ( "Enter a valid get url : " )
print (getReq(url_inp))
elif choice = = 2 :
url_inp = input ( "Enter a valid get url : " )
data_inp = {
"name" : input ( "Name : " ),
"email" : input ( "Email : " ),
"work" : input ( "Work : " ),
"age" : input ( "Age : " )
}
print (postReq(url_inp, data_inp))
elif choice = = 3 :
exit( 0 )
except Exception as e:
print ( "Error : " , e)
|
Output:
First, make the get request
A get request with the query.
A get request to fetch all users.
Lastly, make a post request with JSON data.
Below is the complete output video to depict the functionality of the program
Share your thoughts in the comments
Please Login to comment...