Learning Python Network Programming

(Sean Pound) #1

APIs in Action


By now, you should be able to fully recreate the example document shown at the
beginning of this section. Go ahead and give it a try.


Converting to text

Once we have an XML tree that we're happy with, usually we would want to
convert it into a string to send it over the network. The ET.dump() function that
we've been using isn't appropriate for this. All the dump() function does is print the
tag to the screen. It doesn't return a string which we can use. We need to use the
ET.tostring() function for this, as shown in the following commands:





text = ET.tostring(name)
print(text)
b'Caerphilly'





Notice that it returns a bytes object. It encods our string for us. The default character
set is us-ascii but it's better to use UTF-8 for transmitting over HTTP, since it
can encode the full range of Unicode characters, and it is widely supported by
web applications.





text = ET.tostring(name, encoding='utf-8')





For now, this is all that we need to know about creating XML documents, so let's see
how we can apply it to a web API.


The Amazon S3 API


Amazon S3 is a data storage service. It underpins many of today's high-profile
web services. Despite offering enterprise-grade resilience, performance and
features, it's pretty easy to start with. It is affordable, and it provides a simple
API for automated access. It's one of many cloud services in the growing
Amazon Web Services (AWS) portfolio.


APIs change every now and then, and they are usually given a version number so
that we can track them. We'll be working with the current version of the S3 REST
API, "2006-03-01".


You'll notice that in the S3 documentation and elsewhere, the S3 web API is referred
to as a REST API. REST stands for Representational State Transfer, and it is a fairly
academic conception of how HTTP should be used for APIs, originally presented
by Roy Fielding in his PhD dissertation. Although the properties that an API should
possess so as to be considered RESTful are quite specific, in practice pretty much
any API that is based on HTTP is now slapped with the RESTful label. The S3 API is
actually among the most RESTful high-profile APIs, because it appropriately uses a
good range of the HTTP methods.

Free download pdf