There are plenty of existing resources available that do an excellent job of explaining what node.js is, its benefits, and how to get up and running with a hello world project. This multi-part series assumes you've already read some basics and are looking to start crafting node APIs quickly. We have created a starter project that will bootstrap you in part 2, and demonstrate some best practices for creating and exposing APIs.
What are We Building?
We are going to create an API based on REST principles without going fully into a HATEOAS implementation. To not get bogged down in a complicated domain, we will focus on exposing a fairly straight-forward API for managing users and their todo items. The relationships are represented by the following diagram:
A user can have zero or many todos and a todo has one user.
The basic plan is to implement the following resources:
[sourcecode language="plain"]URL HTTP METHOD PURPOSE =========== =============== =========================== users POST Create a new user users/:userId GET Get a specific user users/:userId POST Update a specific user's information users/:userId/todos POST Create a new todo for a user users/:userId/todos/:todoId GET Get a specific todo users/:userId/todos/:todoId POST Update a specific todo's information users/:userId/todos/:todoId DELETE Delete a specific todo[/sourcecode]
Goals to Get Started
When building a REST API, there are a number of things you should consider:
- How do you plan to authorize and authenticate users?
- What is your persistence mechanism for data? Is it a NoSQL product or a relational database?
- What is your data access strategy for interacting with the persistence mechanism (database, for example)?
- How are you going to securely store sensitive data like passwords?
- You should decide what HTTP responses mean and, in the instance where there is ambiguity such as a 400 Bad Request error, how do you plan to augment that response with additional information so consumers know exactly what happened?
- How are you going to migrate settings from environment to environment, such as local to test to production? (configuration)
- How are you going to keep details of exceptions/internal server errors from getting back to the client, yet still be able to see what happened? How are you going to field or diagnose support calls for those errors?
- How are you going to logically separate your code?
This is a good list to start with and we will address all of these concerns in the example project. A fundamental goal is to remain true to the simplicity of HTTP. Basically, don't just invent something; there is probably a solution for it already.
In this post, we laid the groundwork for what we are going to build and what some basic concerns should be when starting to craft an API. In Part 2, we will get everything set up and start interacting with the starter project.