Learning Python Network Programming

(Sean Pound) #1

APIs in Action


Next, we create our auth object. We'll use this in conjunction with Requests to add
AWS authentication to our API requests.


The ns variable is a string, which we'll need for working with XML from the S3 API.
We'll discuss this when we use it.


We've included a modified version of our xml_pprint() function to help with
debugging. And, for now, the create_bucket() function is just a placeholder.
We'll learn more about this in the next section.


Finally, we have the command interpreter itself - it simply takes the first argument
given to the script on the command line and tries to run a function with the same
name, passing any remaining command-line arguments to the function. Let's give
this a test run. Enter the following in a command prompt:


$ python3.4 s3_client.py create_bucket mybucket


Bucket name: mybucket


You can see that the script pulls create_bucket from the command line arguments
and so calls the function create_bucket(), passing myBucket as an argument.


This framework makes adding functions to expand our client's capabilities
a straightforward process. Let's start by making create_bucket() do
something useful.


Creating a bucket with the API


Whenever we write a client for an API, our main point of reference is the API
documentation. The documentation tells us how to construct the HTTP requests
for performing operations. The S3 documentation can be found at http://docs.
aws.amazon.com/AmazonS3/latest/API/APIRest.html. The http://docs.aws.
amazon.com/AmazonS3/latest/API/RESTBucketPUT.html URL will provide the
details of bucket creation.


This documentation tells us that to create a bucket we need to make an HTTP request
to our new bucket's endpoint by using the HTTP PUT method. It also tells us that the
request body must contain some XML, which specifies the AWS region that we want
the bucket to be created in.


So, now we know what we're aiming for, let's discuss our function. First, let's create
the XML. Replace the content of create_bucket() with the following code block:


def create_bucket(bucket):
XML = ET.Element('CreateBucketConfiguration')
XML.attrib['xmlns'] = ns
location = ET.SubElement(XML, 'LocationConstraint')
Free download pdf