Search Here

Python HTTP GET Request

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       
 

Post a Comment

4 Comments

  1. hello your. I am a beginner to learn Odoo. I hope you can share something about odoo. Maybe that's a book and so on. Thanks

    ReplyDelete
  2. the most stupid thing in this blog is not allowing you to copy code
    how dumb tutorial is this

    ReplyDelete
    Replies
    1. thanks for your comment, we will try to improve it

      Delete