We know what the API should look like. Now we need to build it. In this video, we will define the API’s route handlers and call the API from the client to have a functional application.
- [Narrator] In the previous video, we learned how to write in API specifications. In this video, we will build the API that we designed. In particular, we are going to look at setting up the API routes. We will access the database and the route handler to get, insert or update notes. We will construct a response that follows your REST API guidelines. Finally, we will call the REST API from the browser using ajax calls. By the end of this video, we should have a fully functional application.
First, let's open in index.ajs to add the API routes. As we decided in the previous video, we will be using a notes collection resource and a notes element resource. The collection resource will support the GET and POST methods. And the elements resource will support the PUT and DELETE methods. Here we define the four routes. The collection get route is defined here The collection post is here. Element put is here and element delete is here.
Notice that in the routes, we use the call and followed by the name. Like call and uid here. Express.js will match any urlen coded string in place of the call and uid. So slash friend slash one slash notes and slash friend slash me slash notes will both match this route. In addition to that Express also stores a value and place of call and uid and racked up parameters at uid. We use this information here. Let's now look at what is happening inside this handler.
First, we ensure that the user is signed in. To do that, we create a middlewear function called ensureLoggedIn. It checks if a request has an access token, and access token secret and a twitter id. If it does not have any of those, it sends a 401 unauthorized status code. If the request has all of the login information, we call the next handler. Now let's look at the route handler. Here we use the login user's id and the friend's id from the route to get the notes.
Let's take a look at storage and getNotes. When we send the data to the client, we do not send the data as is. We should follow the representation that we chose in the specification. Our representation only exposes the underscore id and content fields. So we map the notes from the database to notes that only have these two fields. Now that we saw how the get handler works, let's move to the post handler. We can see that it looks very similar to the get handler. There are some differences though. For example, in the post handler, we are interested in getting the data in the request body.
Since the body has the note that the user wants to insert. By default, Express does not parse the body, so we need to use an additional middleware as we did with parse and cookies. Here when you include the bodyParser module, Like the cookie-parser module, the bodyParser module is also written by the developers who built Express. We use the bodyParser module here. Since our data is only gonna be in json, you will use bodyParser.json. The bodyParser parses the request body and saves it in req.body.
We get the notes content from the parse body. After we insert the note to the database, you need to send the representation back to the client including the id. Now let's look at the put method. This method acts on an element resource, so the noteID has to be in the url. To update a document in the database, we use the collections updateOne method. It takes in a filter object. This is used to find the element in the database. It also takes an update object, which indicates the field that needs to be updated and the operations to be performed on them.
Finally, it accepts a call back. Notice that the id is an instance of ObjectID. ObjectID is part of mongodb and is used for all ids We get the ObjectID from the mongodb module as we can see here. We also include the signed-in user's id to ensure that users can only update the notes that they own. In the update object, we see a dollar set. This is one of mongodb's update operators.
Other examples of operators are dollar inc and dollar dec for incrementing and decrementing numbers, respectively. Dollar set is a object of key value pairs that need to be changed in the document. After we update the object, we need to send the updated object. We can do that by using the collections findOne method to retrieve the objects from the database. The last route is the delete element route. This one is relatively simple. We delete the note and sendStatus 200 if there are no errors.
This is all that we need to implement the API. Now, we will let the client application make request to the API. To do that, you will add a main.js to the public directory, then we will open index.ajs to add main.js. Now let's look at how hs requests are made. To create an hs request, we create an XMLHttp request object. We set the onreadystatechange to the call back that we want to get called once the client receives a response.
We call open to build the request. In this case, it is a GET request slash friends slash user ID slash notes. True indicates that the request should be asynchronous. Finally, we call send, send the request to the API server. The post and put methods are different because they need a request body. There are two additional things that we need to do. We need to set the content type header to applications slash JSON. We can also include the charset in the header. This is what makes the bodyParser and the server do its work.
We also need to a request body. We do that by passing the body as a string to XHTTP.send. Let's try to run the app and see what it looks like. Okay I can see all my friends, which is good. Ill select edX. Let's add some notes. Open Education, MIT, Harvard. Alright, looks good.
Let's refresh to see if it works. We can see that our notes were returned by the server. Let's update a note. We will close the Education. Let's also remove Harvard. Let's refresh. Here we have it. EdX is a Close Education for MIT students. In this video, we have built an API around notes. This involves setting up the express routes, accessing the database using the mongodb module and constructing their presentation to conform to the guidelines.
Then, we call the API from the client app. In the next video, we will look at Postman, which is the most popular tool for testing http-based APIs.
This Node.js training course gives you an overview of a RESTful API and the logical steps of building one. It explores three different APIs, focusing on their similarities and differences to effectively implement one. Author Saleh Hamadeh starts off by defining APIs, showing how they can be built on top of HTTP and listing the properties that make an API RESTful. Then learn how to develop Twitter Notes, a sample web application that lets its users leave notes for their Twitter friends. You'll use Twitter's API to implement a login flow and then design a web API. In addition, you'll get a closer look at two other real-world APIs—Facebook API and GitHub API. Finally, learn some best practices to keep APIs secure, maintainable, and efficient.
- Identifying REST resources
- Setting up the development environment
- Consuming a RESTful API
- Creating an OAuth login request
- Getting an access token
- Saving data in MongoDB
- Building a RESTful API
- Looking at APIs in the real world
- Best practices for building RESTful APIs