API Workshop


Making APIs

In this walk through we’re going to make some APIs and test them in various ways.  After doing this you’ll be able to create API mockups and blueprints, test them, and create actual APIs from those and deploy them to a cloud server.  Fun times!

Step 1: Create a Mockup API

Head over to apiary.io to get started.  Click the  “See How Apiary Works” icon near the top of the page.  Don’t get distracted by the cool spinning icon, just click it to get to the next section.

Scroll down to the bottom to either sign in with GitHub (super easy) or create an account with email.

If you’ve never used Apiary before, it’ll ask you to name your first API.  Go ahead and name it something like “myemailusername” or whatever works – the namespace is shared across all of apiary so we can’t all use the same one.  I’ll go with “synedra”.

There’s a message from Jakub there, welcoming you and asking for feedback.  You can give some (like to say you shouldn’t have to see the message) or just click “Close” to move on.

Now we’re in the meat of the thing.  From here you can edit your blueprint and change the behavior of your mocked up API.  The base API is designed to be a notes saving API, but we’re just going to use GET for this example so we can get through the whole thing sometime today.

Change the messages under the GET /notes resource to something more meaningful to you.  “Learn Kung Fu” or “Knit 27 sweaters” or “Pick up the Dry Cleaning”

Step 2: Play with your fake API

Now that you’ve created your fake API, let’s play with it.  First, click the Documentation link to get to the interactive documentation page.  Check out the “GET /notes” by clicking on the GET.  Look, there’s your messages!  So exciting!  You can also test the POST, which will show you what the request and response would be for a POST.  Although it doesn’t really change anything – this is only interactive documentation and doesn’t have a real backend server.  Still, pretty fun!

Look over on the right, under Mock Server.  Copy and paste that string into your browser (probably want to use a new window for this) and… oh, crud, we didn’t make a / resource.  That’s ok, add /notes to the URL and see what happens.  There it is!  Your fake API, out there for all the world to see!  If you want to POST to the URL you’re kind of out of luck at this point unless you want to hack up some quick code. But let’s see if there’s a better way.

Step 3: Test your API using Runscope

Runscope provides a set of tools for testing, monitoring and debugging your API.  Click on the “Try Runscope – Free” link (and as it points out, no credit card is required).  Once you’ve done that, you’ll want to pick “API Debugging” and follow the path through to get an idea what we’ll be doing.  Pick an existing product to check on (I like Github because, well, I like Github!).  Check out the response.  How helpful is that?  You can see the request as well, which is hugely useful when trying to debug why something isn’t working in your own personal application.  The next three pages you can skip through with “Next” and head straight to your Dashboard.

Here, Runscope has provided you with a default bucket for your Github call, which is pretty nice.  The Github API is most likely doing well, like it does, so you’ve got a 200 Ok represented, and the time the request took and a few other handy things.  But we’re not here to test Github, they’ve got people for that.  Let’s test out your mocked up API and see how that works.

Click the fancy blue “New Request” button to create a new request.  Put the base URL for your API there, and click “Launch Request”.  Oops, again, here’s our 404.  We didn’t create a base resource, so we get a 404.  Never fear, we’ll fix this right up. Add /notes onto the end of the request and see how that works out.  Hey, there they are, those messages.  We can click to see the request and the response, and find out what a successful request will look like.

At the top of the page, click “Traffic Inspector” and you’ll end up on a dashboard with all the calls in the bucket you’re in.  Now you can see the 404 we generated as well as the 200 when you asked for the notes.  Let’s try one more – the Apiary blueprint allows for POST actions as well, as we saw.  How will that work in Runscope?  Awesome, it works fine (although it didn’t do anything to the back end).

To finish up this section, head back to your Apiary page, and click Traffic Inspector.  Here we can see a list of the calls which have been made against your mocked API.  Again, failures are represented by red dots, and success by green dots.  Compare the inspectors between Apiary and Runscope.  They’re both perfectly reasonable tools – just use what works for you.

Step 4: Setup App for Google Cloud

So now we’ve mocked up an API, but it doesn’t really do anything, and it’s not running on an actual server.

We’ll put something similar together on a real server next.

There are lots of cloud platform providers, but Google Cloud is the one I’m going to be working with today.  The first thing you’re going to need to do is get your account squared away and download the SDK for your system.  Head over to their Getting Started  page to get started.  Name your project and scroll down a bit.  I use python so that’s what I selected, and my examples in class are going to leverage flask.  So unless you have a python allergy, that will be your easiest path (and the code is basically written for you).

Grab [the appropriate SDK](curl%20https://sdk.cloud.google.com/ bash) for your system and follow the instructions on how to get it up and running.  Source your .bash_profile (or whatever profile resource file you used) and you’re ready to hit the ground running.  Pick Python/Flask then get your system authenticated:

gcloud auth login

The process here is pretty heavily modeled after the Sendgrid Tutorial with the same goals, so if you want a more complex setup you can check on that.  But for now, we’re going with a simpler project just to see how these things work together.

First, edit the sample to have some different content. On the Apiary documentation page, there’s a block under the /notes endpoint that looks like this:

200 (OK)
Content-Type: application/json
  "id": 1, "title": "Jogging in park"
}, {
  "id": 2, "title": "Pick-up posters from post-office"

So, to make this work, we’re going to have to actually edit the code. So far as I know, there’s no magic wand to make the blueprint spit out python code, but it’s really pretty easy. To do this, we’ll need to edit the appengine-try-python-flask/main.py file.

We want our new “real” API to return this stuff when ‘/notes’ is hit. It’s cool to leave the “Hello World” for the base ‘/’ resource, it’s friendlier than a 404. But we do need to change the flask code before grabbing it.

Make sure your system has pip and flask installed:

pip install flask

First, update the import to get json functionality (that’s a comma there, not a period):

from flask import Flask,json

Add some new code directly after this section in the code:

def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'

@app.route('/notes', methods = ['GET'])
def get_notes():
	return json.dumps([{
          "id": 1, "title": "Presenting at FOWA"
        }, {
          "id": 2, "title": "Playing with Drone"

Now run it again on your local system and admire the results that match the GET /notes on the mocked API. Do the Runscope and Traffic Inspector thing if you want, but we’re now ready to get this puppy out into the world.

So, grab the “Download this file” and it’ll plop into your Downloads directory, mostly likely.  You can move it somewhere else or just leave it there, it doesn’t make no never mind.

From the directory above that directory, type:

dev_appserver.py appengine-try-python-flask

Wait a few seconds until it says your system is up (hurray!) and you can visit your

API at the localhost:8080. That’s great for you, but not so great for other people who want to visit your site. In the meantime, let’s check that local server and see if it behaves as we expect (‘hello world’ on a ‘/’, gives you your notes on a ‘/notes’ call. Great!

At this point you could deploy the system directly to the cloud and solve the problem where it’s kind of fragile, not available via the external world, and generally only good for quirky dev things. So let’s leverage Runscope again to create a passageway in the internet back to your home server. Download the appropriate Passageway tool for your platform and start it up. Answer a few questions (remember we’re using port :8080) and then it’ll give you a gateway to be used to access your local system out in the wild.  Create a new endpoint or two in Runscape and watch what happens as you and others visit the page.

Step 4: Deploy your app to the cloud

Back to the Google Cloud page you go to get yourself finished.  Click on the “Create your Project” button and it will create the backend server for your cloud instance (and give you a snazzy server name with random words).  Wait a minute or so while it spins up, then deploy your code (again, from the directory above the directory with your code):

appcfg.py -A <your assigned server name> update appengine-try-python-flask

Note that there’s a minor typo in the Google Docs there, you’ll need to use “-flask” in order to deploy the right thing.

That’s it for this section of the workshop. Exercises left to the user are to get POST and DELETE working (for examples of this, see the send grid example above). Add some fancier python to do calculations or lookups, and increase the complexity of what you’re working with.


Dialogue & Discussion