Learning Python Network Programming

(Sean Pound) #1

APIs in Action


JSON doesn't have a tuple data type, so the json module will cast it to a list.
If we convert it back:





j = json.dumps(('a', 'b', 'c'))








json.loads(j)





['a', 'b', 'c']


It will still remain a list. The json module doesn't support sets, so they also need
to be recast as lists. Try the following commands:





s = set(['a', 'b', 'c'])








json.dumps(s)





TypeError: {'a', 'c', 'b'} is not JSON serializable





json.dumps(list(s))





'["a", "b", "c"]'


This will cause problems similar to the ones caused by tuples. If we convert the JSON
back to a Python object, then it will be a list and not a set.


We almost never encounter web APIs that need these kinds of specialist Python
objects, and if we do, then the API should provide some kind of convention for
handling it. But we do need to keep track of any conversions that we would need to
apply to the outgoing or the incoming objects, if we were storing the data locally in
any format other than that of lists or dicts.


Now that we have an understanding of JSON, let's see how it works in a web API.


The Twitter API


The Twitter API provides access to all the functions that we may want a Twitter
client to perform. With the Twitter API, we can create clients that search for recent
tweets, find out what's trending, look up user details, follow users' timelines, and
even act on the behalf of users by posting tweets and direct messages for them.


We'll be looking at Twitter API version 1.1, the version current at time of writing
this chapter.


Twitter maintains comprehensive documentation for its API,
which can be found at https://dev.twitter.com/overview/
documentation.
Free download pdf