How to do GET and POST requests using Python?
To make HTTP requests in python, several HTTP libraries (e.g. httplib, urllib, requests) are available to download. But the most famous and simple library is the requests lib and today we gonna talk about it.
1. Download and install requests library
$ pip install requests
2. Creating a Get request
# importing the requests library import requests # create new getRequest function def getRequest(requests): endpoint = "http://openlibrary.org/api/books" params = {'bibkeys':'ISBN:0201558025'} r = requests.get(url = endpoint, params = params) data = r.text print("Get Reponse:%s"%data) # call the getRequest function getRequest(requests)
Output
Get Reponse:var _OLBookInfo = {"ISBN:0201558025": {"bib_key": "ISBN:0201558025", "preview": "restricted", "thumbnail_url": "https://covers.openlibrary.org/b/id/135182-S.jpg", "preview_url": "https://archive.org/details/concretemathemat00grah_444", "info_url": "http://openlibrary.org/books/OL1429049M/Concrete_mathematics"}};
3. Creating a Post request
# importing the requests library import requests # create new postRequest function def postRequest(requests): endpoint = "http://<your-domain>/api/<post-method>" data= {'test':'Hello World'} r = requests.post(url = endpoint, data= data) data = r.text print("Get Reponse:%s"%data) # call the postRequest fucntion postRequest(requests)
Output
Get Reponse:{"statusCode":200}
Thatβs it. I hope this will help. ?
Photo: https://www.brandeps.com