Using REST web services and JSON

Representational State Transfer (REST) web services use the REST-architectural style (for more information refer to http://en.wikipedia.org/wiki/Representational_state_transfer). In the usual context of the HTTP(S) protocol, we have the GET, POST, PUT, and DELETE methods. These methods can be aligned with common operations on the data to create, request, update, or delete data items.

In a RESTful API, data items are identified by URIs such as http://example.com/resources or http://example.com/resources/item42. REST is not an official standard but is so widespread that we need to know about it. Web services often use JavaScript Object Notation (JSON) (for more information refer to http://en.wikipedia.org/wiki/JSON) to exchange data. In this format, data is written using the JavaScript notation. The notation is similar to the syntax for Python lists and dicts. In JSON, we can define arbitrarily complex data consisting of a combination of lists and dicts. To illustrate this, we will use a very simple JSON string that corresponds to a dictionary, which gives geographical information for a particular IP address:

{"country":"Netherlands","dma_code":"0","timezone":"Europe/Amsterdam","area_code":"0","ip":"46.19.37.108","asn":"AS196752","continent_code":"EU","isp":"Tilaa V.O.F.","longitude":5.75,"latitude":52.5,"country_code":"NL","country_code3":"NLD"}

Note

You can get this data from http://www.telize.com/geoip/46.19.37.108.

The following is the code for the json_demo.py file:

import json

json_str = '{"country":"Netherlands","dma_code":"0","timezone":"Europe/Amsterdam","area_code":"0","ip":"46.19.37.108","asn":"AS196752","continent_code":"EU","isp":"Tilaa V.O.F.","longitude":5.75,"latitude":52.5,"country_code":"NL","country_code3":"NLD"}'

data = json.loads(json_str)
print "Country", data["country"]
data["country"] = "Brazil"
print json.dumps(data)

Python has a standard JSON API that is really easy to use. Parse a JSON string with the loads() function:

data = json.loads(json_str)

Access the country value with the following code:

print "Country", data["country"]

The previous line should print the following:

Country Netherlands

Overwrite the country value and create a string from the new JSON data:

data["country"] = "Brazil"
printjson.dumps(data)

The result is JSON with a new country value. The order is not preserved as it usually happens for dicts:

{"longitude": 5.75, "ip": "46.19.37.108", "isp": "Tilaa V.O.F.", "area_code": "0", "dma_code": "0", "country_code3": "NLD", "continent_code": "EU", "country_code": "NL", "country": "Brazil", "latitude": 52.5, "timezone": "Europe/Amsterdam", "asn": "AS196752"}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.98.148