Python HTTP GET Request - BOOKC -->

Python HTTP GET Request

Tuesday, February 19, 2019

In this tutorial I will show you how to get data from API using python HTTP GET request. And the API return response in XML. We will also read data from that XML response using python "ElementTree" library.



Python HTTP GET Request

Python HTTP GET Request

To consume API using python we need to "import requests" library of python.

import requests
r = requests.get("http://your_api_url_goes_here")       
 

Here "r" is the response object and from that object we can get all the information that we need. And you can do that simply by using HTTP GET Request of python.

r.status_code      
 

We can check the response of above API by using "status_code". If status code is equal to 200 its mean that API working fine, and if it returns 400 it means something bad in request.

r.content      
 

To get or read data from response object we use "r.content".

As we have already discussed that our API returns XML so to read data from XML response we need to import "import xml.etree.ElementTree as ET" in our code. The complete code snippet is below.


import xml.etree.ElementTree as ET
import requests
r = requests.get("http://your_api_url_goes_here")
if r.status_code == 200:
 root = ET.fromstring(r.content)  
 data = root.text