Monday, February 27, 2017

Calling REST Seb service and parsing JSON DATA using Pyhton


JSON is now a standard way of sending and consuming data between different application using Web service.
JSON allows simple and clean way of data dealing between different application i.e. sender and consumer. In due course of time JSON api are availbale in all the language i.e. python, JAVA, JS, .net etc
Below we example show how to consume REST JSON API http://services.groupkt.com/country/get/iso2code/IN and consume one of its parameter in response
import json
import requests
from requests.auth import HTTPDigestAuth

# Replace with the correct URL
url = "http://services.groupkt.com/country/get/iso2code/IN"
myResponse = requests.get(url)
# check api response is (OK = 200)
if(myResponse.ok):
print("----myResponse.content-------"+ myResponse.text)
jData = json.loads(myResponse.content.decode('utf-8'))
print(jData)
locations = jData['RestResponse']['result']['alpha2_code']
print("locations"+locations)
else:
myResponse.raise_for_status()
Out Put :
----myResponse.content-------{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Country found matching code [IN]." ],
"result" : {
"name" : "India",
"alpha2_code" : "IN",
"alpha3_code" : "IND"
}
}
}
{'RestResponse': {'messages': ['More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm', 'Country found matching code [IN].'], 'result': {'name': 'India', 'alpha2_code': 'IN', 'alpha3_code': 'IND'}}}
locationsIN

Note :- REST JSON Response 
{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Country found matching code [IN]." ],
"result" : {
"name" : "India",
"alpha2_code" : "IN",
"alpha3_code" : "IND"
}
}

No comments: