Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

Building APIs

You have already been introduced to NodeJS which allows for JavaScript to be run efficiently on a web server. In the exercises you interacted with the server through the Terminal window. In this worksheet you will be applying your existing skills to build an API that adheres to REST principles. By the end of the worksheet you will be in a position to start designing and building your own as part of your module assignment.

Before you start this or any other worksheet you should make sure you have the latest commits from the upstream repository on GitHub.

There is a slide deck https://goo.gl/39SKVJ to accompay this worksheet. Make sure you are familiar with its contents before proceeding.

git pull upstream master

1 Principles of REST

REST is an architectural style that defines a series of principles that define how to interact with online resources.

  1. resources define the nouns in the API and each should be defined with a unique URL.
  2. resources should be organised into collections.
  3. interactions are the verbs and should use standard HTTP methods in agreed ways.
  4. communication should be stateless (each request should be self-contained and not rely on any server-state).

The todo/ directory contains a simple API that demonstrates these key concepts. The first step is to run it and interact with it to understand these REST principles and how they are implemented.

To test your API you will need to connect using the Postman tool and to do this you will need to find the external URL of your Codeanywhere workspace. This can be found by right-clicking on the container title in the left sidebar as shown.

Accessing the External URL

Before starting this worksheet you should update the node installation to the latest version. Instructions can be found in the previous worksheet (04 Introduction to NodeJS).

  1. use the terminal to navigate to the todo directory and install the module dependencies using npm install restify csprng. This will install the restify, xmlbuilder and csprng modules. Take a few moments to read through their documentation.
  2. start the API in CodeAnywhere by running the routes file node index.js.
  3. right-click on the container title in the left sidebar and choose info.
  4. locate and copy the public URL of your container. It will look something like this: http://preview.xxx.box.codeanywhere.com/.
  5. install and open the Google Chrome Postman plugin and paste in the url you just copied. Remove the trailing / and add the port number to the end so your url looks like this: http://preview.xxx.box.codeanywhere.com:8080. Click on the Send button.
  6. now try the http://preview.xxx.box.codeanywhere.com:8080/lists URL. Why does it return the same result (study index.js carefully).
  7. each request returns a response code that indicates its success or failure. Look up the response code to find out more.
  8. the response also includes a body which contains any data returned from the API. Notice that the data is returned in JSON format. The data returned is known as its representation.

2 Collections and Resources

You need to fully understand the concepts of Collections, Resources and their Representations. We will learn about these by interacting with the lists API.

The /lists url represents a collection of lists. We can add, view, update and delete individual lists. These actions correspond to standard database CRUD operations. lets investigate how this works. As you complete each activity, read the source code to make sure you understand how it works.

  1. perform a GET /lists operation. This is what you did in step 5 in the previous activity. Notice that this returns an error (we haven't added any items yet!)
  2. perform a POST /lists request. the POST method indicates we want to add a resource to a collection. In the request body you need to include some json data in the request body (choose the raw tab and paste in the json data below). Notice the response includes a list id.
{
    "name": "shopping",
    "list": [
        "Cheese",
        "Bread",
        "Butter"
    ]
}
  1. repeat the POST request to add a second resource ['red', 'orange', 'green', 'blue', 'purple'].
{
    "name": "colours",
    "list": [
        "red",
        "orange",
        "green",
        "blue",
        "purple"
    ]
}
  1. repeat the GET /lists request. This should now return the lists collection. The list contains the list names and the unique id for each list which can be used to access details for an individual list.
  2. each list resource has its own unique URL. Perform a GET /lists/xxx request, where xxx is one of your list ids. The API should return the specified list.

2.1 Test Your Knowledge

  1. Currently we can add and view resources (create and retrieve in CRUD terms). Use the code stub in index.js to implement a mechanism to allow resources to be deleted.
  2. Finally implement a mechanism for resources to be updated using the PUT method.

3 Deploying to Heroku

Heroku provide a free hosting tier and make it really easy to deploy your API. Unline other material in this module you will need to be working with a separate git repository containing only a single NodeJS project, your assignment API for example. Start by creating a free Heroku account.

Once you have created your account and logged in you need to download and install the Heroku Toolbelt. Once this is installed you need to log in.

wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh
heroku login
Enter your Heroku credentials.
Email: username@email.com     
Password (typing will be hidden):
Authentication successful.

Next you need to navigate into the root of your Git repository and create a new Heroku project, replacing project-name with your chosen project name. Each hosted project need to have a unique name so your first choice may not be available.

heroku create project-name
Creating project-name... done, stack is cedar-14
https://project-name.herokuapp.com/ | https://git.heroku.com/project-name.git
Git remote heroku added

This will create a new project on the Heroku servers and will also add a heroku git remote. You can check this has happened.

git remote -v
heroku	git@heroku.com:project-name.git (fetch)
heroku	git@heroku.com:project-name.git (push)
origin	git@github.com:username/api.git (fetch)
origin	git@github.com:username/api.git (push)

If you need to add the remote manually you can find the correct procedure by loading the dashboard page, selecting your app then choosing the Deploy tab.

4.1 Test Your Knowledge

You have already build a simple API so lets see if we can deploy it to a live server.

  1. Create a new GitLab remote called todo.
  2. Clone this empty repository into a new project.
  3. Copy in the contents of the todo/ directory.
  4. Install and configure the Heroku Toolbelt using the instructions above.
  5. Deploy your API to the Heroku cloud.
  6. Check it is working.

Presentation

https://goo.gl/KWyi4l

Homework

For your homework you will be required to read up on the purpose of APIs and how to design them.

  1. APIs for Dummies
  2. Web API Design
  3. RESTful Web Services

Development Stages

  • Plan your API public interface (write stub routes)
  • Write acceptance tests (these will fail)
  • Write a module to extract the data you need from API (TDD)
  • Write the module to persist your data (TDD)
  • For a higher grade write a module to handle user auth (TDD)
  • Implement each route (functionality in the model) (TDD)
  • Use integration tests for your model
  • Make sure your acceptance tests pass