In the previous chapter, we built a service that reads tweets from Twitter, counts the hashtag votes, and stores the results in a MongoDB database. We also used the MongoDB shell to add polls and see the poll results. This approach is fine if we are the only ones using our solution, but it would be madness if we released our project and expected users to connect directly to our MongoDB instance in order to use the service we built.
Therefore, in this chapter, we are going to build a RESTful data service through which the data and functionality will be exposed. We will also put together a simple website that consumes the new API. Users may then either use our website to create and monitor polls or build their own application on top of the web services we release.
The code in this chapter depends on the code in Chapter 5, Building Distributed Systems and Working with Flexible Data, so it is recommended that you complete that chapter first, especially since it covers setting up the environment that the code in this chapter runs on.
Specifically, you will learn:
http.HandlerFunc
types can give us a simple but powerful pipeline of execution for our HTTP requestsFor an API to be considered RESTful, it must adhere to a few principles that stay true to the original concepts behind the Web, and are already known to most developers. Such an approach allows us to make sure we aren't building anything strange or unusual into our API while also giving our users a head start towards consuming it, since they are already familiar with its concepts.
Some of the most important RESTful design concepts are:
GET
methods will only ever read data, while POST
requests will create somethingFor an in-depth overview of these and other details of RESTful designs, see the Wikipedia article at http://en.wikipedia.org/wiki/Representational_state_transfer.
The following table shows the HTTP methods and URLs that represent the actions that we will support in our API, along with a brief description and an example use case of how we intend the call to be used:
Request |
Description |
Use case |
---|---|---|
|
Read all polls |
Show a list of polls to the users |
|
Read the poll |
Show details or results of a specific poll |
|
Create a poll |
Create a new poll |
|
Delete a poll |
Delete a specific poll |
The {id}
placeholder represents where in the path the unique ID for a poll will go.