
This video will show you how to validate your set up and get started with a sample project
This video will show you how to set up an Express server and test it using a sample request.
Now that you have your environment and tools set up you’re ready to move onto our first hands-on lesson. Using the sample code we’ve already created, we're going to replace the single piece of text that we've been returning from our REST API method, and we're now going to create an array of data to return.
We can also modify the status code by using the status method on the response. We should always add a status code response and make sure we're using the appropriate status code to indicate how the request went.
In this video I demonstrate how to change from a single value response to an array of responses and also how to use the status method as part of the response object.
If you’re not already familiar with JavaScript Object Notation (JSON) you might want to read through the examples on json.org to understand this format a little better since we’re now going to talk about using JSON objects and envelopes.
Instead of just sending the array of data, it's a better practice to actually wrap everything into a JSON object. So in this particular case, we’re going to wrap a JSON object around the data. Then adding the data into a property. We can then add in the status, status text, a message if you wanted to display one or for troubleshooting and it gives us a way to send additional data.
There is no real standard for what you have to return in your response but what we’re going to see in our video demo is a pretty common scenario for how most applications handle response data.
In This video I demonstrate how to create a JSON object and put that into the response along with additional property information you might want on the client.
Another best practice that you should follow when writing your REST API methods is to separate your logic out. This makes your work easier to maintain. We have controllers, which is what we have in our index.js, and then we have the logic to retrieve data. We want to separate those out. So what we're going to do now is we're going to create a module for the data.
In this video I demonstrate how to separate your controller from your data retrieval logic.
Now that you have a new module for your data, we can start to create even more abstraction by learning how to read the data from a different location. In this example, we’re going to look at how to read the cities data from a file.
In this video I demonstrate how to read data from a JSON file and return that data in our API response instead of hard-coded data.
At this point we’ve seen how to get all of the data but sometimes we want to return a single piece of data or just some of the data. When we are searching for data inside of our JSON file we often do this based on a unique value, such as an ID, which is the property we’re going to use to locate a specific item in our JSON. This means we’ll need to have a function that takes in an ID and then only returns the JSON object associated with that ID.
In this video I demonstrate how to create a function that searches for a specific JSON object based on an ID property.
Alternatively, we often want to search for a non-unique piece of information such as color, price, or other factor and return a set of search results. Based on what you have learned so far, it is fairly easy to add an additional function that would support searching through your data.
In this video, I demonstrate how to create a function that searches through the JSON for objects that meet certain criteria to create a result set.
In the first module, I talked about different browser verbs and how we can use them to indicate we are wanting to perform various operations. We’re now going to look at how we can modify data by adding an Insert method to our module. The insert method will take in this new information, create new JSON and add it to our file.
In this video, we will create an insert method that takes in new information from the client and adds it as JSON to the existing file.
Now that you’ve seen how easy it is to insert data to our Express server, we’ll look at how we can update existing data using an Update method. In a similar way to when we searched for a specific piece of information to retrieve, we need a unique identifier like an ID to be able to determine which object we want to update. PUT is the verb we use when we want to make changes.
In this video, we will create an update method that uses a unique ID to update existing object data.
Deleting data is a fairly straight-forward exercise where we once again need to make sure we have a unique identifier for the object we want to delete and then search for it and remove the item from the JSON file.
In this video, we will create a delete method that uses a unique ID to remove an existing object from the JSON file.
In this video I will use the XMLHttpRequest object to call our REST API that we’ve created in the previous section. We also set up our API to allow CORS requests.
Now that you have your MongoDB installation, we can now install Mongoose into our project and look at how to connect to and work with our database.
In this video, I will show you how to install Mongoose and connect your JavaScript API application to your database.
With Mongoose, everything is derived from a Schema, which allows us to add references to define objects we want to store. We’re going to set up a Schema to define a Member object that has a username.
const memberSchema = new mongoose.Schema({
username: String
});
Once you have defined your Schema, you then compile it into a Model.
const Members = mongoose.model(‘Members’, memberSchema);
A model is a class with which we construct documents. In this case, each document will be a member with properties and behaviors as declared in our schema. Now we can create a specific instance of one of our members with the username “Stanley”.
const member1 = new Member({ username: 'Stanley' });
console.log(member1.username);
In this video, I will show you how to create your first Schema and compile it into a Model in Mongoose.
As you’ve seen in the previous section, CRUD operations are the backbone of any data-driven application. Now that you’ve seen how to get started with data in Mongoose, we’re going to look at the various CRUD operations and how to use them.
Adding a New ItemThe first thing we’ll want to do with our database is to add some information (documents) so we can query them. We will do this by setting up a POST request with the data we want to apply to our Schema and ultimately store it as a document in the database.
In this video, I will show you how to create a POST request to store information in your database.
Querying in Mongoose allows you to find specific documents using methods built into your compiled Models. These are find, findById, findOne, and where. Mongoose also supports more advanced methods of querying data. This is a very similar process to the earlier lessons on getting all data or specific data based on a unique identifier.
In this video, I will show you how you can use your API to query for all items or a specific document using Mongoose.
Updating existing document information is done through a PUT request. This should look similar to the GET request for a single ID except we are taking in the body parameters that you want to update the document with.
We’re also going to use the method findByIdAndUpdate which takes three main parameters, an ID, an object corresponding to the user whose values will be updated, and of course, a callback function. You’ll be passing along the request body as the second parameter, the object, as it will already be parsed correctly with the middleware we required and used at the top of MemberController.js.
A good practice when updating some values is to request the updated value to be sent back to you. This is important as you want to have access to the newly updated value. Hence, you add another, fourth parameter {new:true} which stands for the option of which version of the value, in your case the user, you want to return. The one before the update, or the one after. Returning this value will show you the user you updated.
In this video, I will show you how to use Mongoose to update an existing database document with new information.
The router.delete looks almost exactly like the router.get and allows us to remove a member from the database by their ID. the findByIdAndRemove works very similarly to findById but has the additional delete step built-in.
In this video, I will show you how use Mongoose to delete an existing database item by ID
In this video, we’re going to look at how to upload files to our REST API using HTML forms using a synchronous XMLHttpRequest.
So as I discussed, using synchronous events isn’t really how we should do things so now we’re going to look at how we can upload these files asynchronously. By default, we typically use asynchronous calls and we’ll see how this is done in the demo.
Now an important thing to keep in mind when we're talking about asynchronous XHRs is before we start doing anything, like open methods and send methods, we want to set up our event listeners. Otherwise, things can start to happen and get ahead of us and we might lose some of those events. So up here between the construction of the XHR and before the open method call, I'm going to set the responseType property equal to blob. Blob response means that we're going to get something binary. Now in this case, we're going to get the image that we submit directly sent back to us. So that's going to come in as a data‑type blob, and then we can use that in response to populate an image tag, which is kind of our goal here.
In this video, we’re going to look at how to upload files to our REST API using HTML forms and an asynchronous XMLHttpRequest.
Most of the things that we talked about in the last section regarding uploading single files also apply to uploading multiple files. However, there are some special things to keep in mind and some patterns that you might want to be aware of, so we're going to cover those in this section.
In this video, we’re going to look at how to upload multiple files to our REST API using HTML forms and a synchronous request.
In this video, we’re going to look at how to upload multiple files to our REST API using HTML forms and an asynchronous XMLHttpRequest.
In this video I provide an overview of the three different ways Express.js provides for sending files from the server to the client along with a demo of each.
In this video, I will show you how to set up your application to create and sign tokens so that users can be registered to use your application with JSON Web Tokens.
Now that you have a user with a token, we can look at how users log in.
Let’s first look at the structure of the login request.
The payload for our request will be a username and password. So it will look like:
{
“Username”: “member”
“Password”: “member123”
}
Once this information is passed, assuming the credentials are valid, the system will then return a new JSON Web Token. First, we’ll look at our request in more detail so you understand what you are sending and how this works.
The Header:
{
“alg”: “HS256”,
“typ”: “JWT”
}
This information tells us which algorithm has been used for encoding the data and the type of token JWT for JSON Web Token.
The Payload:
{
“Exp”: 1550946689,
“Admin”: false
}
The Iss contains the username of the logged-in user. This is helpful if we want to show this on the UI or do any logging with this information.
The Exp is the expiration information about the token. You’ll want to determine how long users should be allowed to be logged in before they will have to use their credentials again.
Admin is a boolean that describes the role of the user.
Now we can create the actual token by encoding the above items and signing the resulting values.
We can use Bcrypt’s compareSync() method to compare the password sent with the password in the database. If they match, then we can sign() the token.
Of course one of the most important parts of authentication is actually testing the users who are accessing your API to be sure they belong there. Permission Middleware is important here since we have to create a bridge between different parts of our code in order to perform this test.
When we create a request to an endpoint, the router has the option to pass the request on to the next middleware function in line. Next is literally the name of the function in question so this makes it easy to remember.
We can see how to use next() in our /me router by creating a middleware function to check the validity of tokens.
In this video, I will show you how to use the next() function in your router to send the endpoint request to a middleware function that checks the validity of JSON Web Tokens.
The end result: when a user tries to access any API resource, the middleware code is executed first. The token is received from the header and stored in a token variable. Then this token is verified using the secret key and by checking if the token is available in the respective users' database, if the token is valid then the user data is fetched and passed to the calling function.
In this video, I will demonstrate how to use the localstorage to create a way to save, retrieve, and remove carts that have been stored.
So, let's look now at how we deal with data from a REST API. Why might you want to store data that you pull from an API in local storage? What scenarios is this suitable for? And what are the pitfalls that you need to look out for? So, why might you want to store data that you've pulled from an API?
The answers to these questions really depend on the kind of data we are working with.
In our scenario, we have a service that provides us with a list of products. Each product has a description and a unit price. Now, this data rarely changes, so it doesn't make much sense to call our servers every time a page is loaded. A better strategy might be to fetch the data once and store it locally. Doing so is going to vastly reduce the number of outbound calls our page makes to the product service and because we have less outbound traffic, we end up with a more responsive website. There's also going to be less load on our product service, meaning we can operate it at a lower scale, which could give some potential cost savings, too.
On the opposite, if you had a service that provided frequently changing data, perhaps stock prices or something similar, then it wouldn't really be something that you'd want to store. Another consideration is the type of data. Remember, you have to store the data as a string, and it needs to be able to fit within the storage limit. Trying to store large quantities of complex data probably isn't going to be a good idea.
So now let’s look at how we can retrieve data from our ProductService API and store it in local storage.
In this video, I will show you how to store and retrieve data from LocalStorage from your API Data.
We're going to look at polling our API and how we can keep track of when it was last updated. By the end of this section, our app should only be calling the API when it believes the API data may have gone stale. At the moment, there's nothing in our API or our app, for that matter, that gives us any indication of when the data was created or when it was added to storage. It could be an hour old, or a week old, or even older. Now, we're fortunate in this scenario in that we control both the API and the web app codebase. That means we're free to make changes to the design to suit our needs. But that's not always the case. What if you can't make changes to the API? Well, one option we have is polling. This means we can set a schedule for when we update.
When the page loads for the first time, we make a request to the API and pull down the product data. We then repeat this on a set schedule. This ensures that our product data is regularly updated.
In this video, I will demonstrate how to poll an API to refresh data on a schedule.
If you are fortunate enough to control the API and are able to make changes, then you can provide a better solution to determining how fresh your data is. The simplest option is to add a timestamp to the JSON that shows when it was last updated. This way, the client would know when the data was last updated and we could store that value within the local storage and use it to help us know when it is time to update.
In this video, I will show you how to modify your application so you can use a timestamp to help determine when API data should be refreshed in the local storage cache.
This course will teach you how to write, use, and consume REST APIs in JavaScript.
Application Programming Interfaces (APIs) are constructs made available in programming languages to allow developers to create complex functionality more easily. They abstract more complex code away from you, providing some easier syntax to use in its place.
Client-side JavaScript, in particular, has many APIs available to it — these are not part of the JavaScript language itself, rather they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code. While there are many APIs available in JavaScript we often have to write our own custom API to allow transitions and access to data in our application.
A REST API is a way of easily accessing web services. When a RESTful API is called, the server will transfer to the client a representation of the state of the requested resource. A RESTful API is stateless, separates concerns between client-server, allows caching of data client-side and it utilizes standardized base URLs and methods to perform the actions required to manipulate, add, or delete data.
Each section is designed to be completed in one day, along with a hands-on practice activity to be completed before moving on to the next module.
This course assumes the following as prerequisite knowledge:
Intermediate to Advanced JavaScript
Use of the Browser DOM
Use of database CRUD transactions
Basics of Node.js