The course is part of this learning path
In this course you will learn how to create API routes for an Express server.
- Implement a GET route handler
- Define what is the root entry point of an API
- Understand the request and response objects
- Define and implement the res.json() method
- Implement a POST route handler
- Implement the express.json() middleware to parse JSON requests
- Define and implement the res.body method
- Learn how to use Insomnia to test an API endpoint
- Implement a wildcard endpoint to handle requests that go to a non-existent endpoint
- This course is intended for anyone who wants to learn about Express.
Introduction to Express - Express Routing. Routing refers to determining how an application responds to a client request to a particular API endpoint. Endpoints refer to points of communication your API may offer to a client. Transitioning to the lab IDE. On the screen, I have an Express environment in the server.js file. For this video, I'm going to create three routes. Beginning with the initial route, I will type app.get. The app variable represents the top level Express function. The get method defines a route handler for GET requests to a given URL. For this route, I need to pass in two arguments. First, the entry point of the route. So, for this I will use a forward slash(/). Then the arrow function. The arrow function will have two arguments.
The first argument, req for requests, and res, short for response. And these two arguments represent two special objects, the request object that handles any requests sent to the server, and a response object that will handle any response sent by the server. So, focusing on this entry point structure and what this forward slash(/) represents. The forward slash(/) represents the root URL. For example, this would be www.cloudacademy.com. Notice this forward slash at the end of the URL. That is the same forward slash that's being represented here. Traditionally when creating an API, we start off with a root entry point. The root URL is for serving the pages on the site. The root entry point, which comes after the forward slash, is the main entry point for the API. And what is a root entry point?
Typically, it's the main entry point to a service, such as an API. To create a root entry point, I will type api after the forward slash, and this creates an entry point at the URL www.cloudacademy.com/api. Now this route is a GET route, and when a GET request is sent to your server, the goal from the requester is to retrieve data, the request is to get data. And in order to send back data, I need to send back a response.
So, I'm going to be using a special method from the response object. Inside of the arrow function, I will type res.json(), and inside of these parentheses, I'm going to send back an object with a property of API and a string value of API route. The JSON method, that is part of the response object, will take an argument and send it back as JSON. Behind the scenes this is using the JSON.stringify method to accomplish this task. Now this route is ready to test out. In the terminal, I will start the server and I will transition to another window. Currently, I'm in another tab inside of the Chrome browser. I've enlarged the address bar for better viewability.
This is the lab URL, and I'm going to replace everything after the first forward slash with API to match the root entry point that I created for this route. Now on the screen is the API response. The reason why the JSON looks very clear and easy to read is because I'm using a Chrome extension called JSON Formatter. So, this route works and I will transition back to the IDE. Now, I'm going to create a post route, and the post route is meant to receive requests of data that are supposed to be saved to the server's database. Now this Express server doesn't have a database, but that does not mean I can't accept POST requests.
I will begin by typing app.post(), and for the first argument, I'm going to start with the root entry point /api and add an additional endpoint /adduser, which is now the endpoint for the specific post route. And what is an endpoint? An endpoint is a location from which APIs can access resources they need to carry out their function. As the route name implies, this API's function is to add a user, and now once again the second argument for this route is an arrow function with the request and response objects. Now this route is a post route which means it's going to receive a request, and the request is going to be sent in JSON format. In order to handle this request, I need to use a special express method.
Up above, I'm going to type app.use(), and inside of the parentheses, as an argument express.json. This express.json function should not be confused with the res.json function used earlier in the video. Express.json is a middleware function that parses incoming JSON requests. Middleware, as the name implies, is a function that occurs in the middle of the request and response cycle. When the post route receives a JSON request, the middleware will parse it. Going back to the post route, inside of the arrow function, I will type res.json passing in the argument of req.body.
The body is a property of the request object that is populated with data. The data comes from the express.json middleware. If I do not use this middleware, the body portion will be undefined. Now, because I'm not working with the database, when this route receives a request, whatever is in that request will be sent back as a JSON response showing that the request is working and responding properly. I'm going to start the server, and to demonstrate this, I will transition to a tool called Insomnia. Insomnia is used for API testing. I'm going to do a quick tour off the screen.
To the left of the address bar is a dropdown to select the type of request to be tested. I will change GET to POST. The address bar is for the API URL that I wish to test. I will paste in the lab URL and change the entry point after the first forward slash to api/adduser. Underneath the POST request is another dropdown that is currently set to the default body. This is to set the format of the request that will be sent. I will change it to JSON, and then in the panel below, I will write a JSON object. Curly brackets with a property value of first name. Note this is JSON, so I need to use double quotes over any property name. Colon, and in double quotes, my first name. Now the panel to the right is the response panel. If I wrote my route correctly, I should see a response from the server that matches the JSON I'm sending to the server. I will click on 'Send' and there is the response.
So, this works. I want to transition back to the IDE. For the last route in this video, I'd like to demonstrate how to handle a specific edge case. When a request is sent to a non-existing endpoint. Right now, I have /api and /api/adduser. What if the wrong endpoint is typed after /api? I'm going to use a wildcard route to manage this specific situation. To begin, I'm going to copy the /api get route and paste it down below. After the /api, I'm going to add a /*, and the asterisk is a wildcard character representing anything tight after the forward slash. Inside of the res.json method, I'm going to change the message from api route to 'api route not found'. Before testing this route out, I need to explain one specific role. Express route handily goes in order based on the order the routes are written. Whatever route is first is checked first when a request is sent to the server.
So, the wildcard route always needs to be the last route written. Last, as in, the bottom-most route inside of the file. This is location-based within the file as routes are read from top to bottom. Otherwise, this could interfere with existing routes. I'm going to start the server and transition back to Insomnia to test this route. Over here, I'm going to change the POST to a GET for this request and remove the JSON. I'm going to change the endpoint from add user to a non-existent route, fake route. I will click on 'Send' and to the right is a response; api route not found. The wildcard route will work with any route endpoint that does not exist after the /api. And that's it. Thanks for watching at Cloud Academy.
Farish has worked in the EdTech industry for over six years. He is passionate about teaching valuable coding skills to help individuals and enterprises succeed.
Previously, Farish worked at 2U Inc in two concurrent roles. Farish worked as an adjunct instructor for 2U’s full-stack boot camps at UCLA and UCR. Farish also worked as a curriculum engineer for multiple full-stack boot camp programs. As a curriculum engineer, Farish’s role was to create activities, projects, and lesson plans taught in the boot camps used by over 50 University partners. Along with these duties, Farish also created nearly 80 videos for the full-stack blended online program.
Before 2U, Farish worked at Codecademy for over four years, both as a content creator and part of the curriculum experience team.
Farish is an avid powerlifter, sushi lover, and occasional Funko collector.