0% found this document useful (0 votes)
113 views18 pages

CS 465 Module Five Full Stack Guide

Uploaded by

b8jacks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views18 pages

CS 465 Module Five Full Stack Guide

Uploaded by

b8jacks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CS 465 Module Five Full Stack Guide

Module Five: RESTful API

In this module, you will begin creating RESTful API endpoints for the code while also integrating with
MongoDB. The purpose of this assignment is to set up Module Six, which is when you transition the
application into a single-page application (SPA) that uses the API calls to fetch and manipulate data.

Create Git Branch for Module Five


Before you begin, you must create your new branch in Git for Module Five. To create your new branch,
in a PowerShell window in the travlr project directory, enter the following command:

git checkout -b module5

Creating the Structure for a RESTful API


Create a top-level folder in the travlr project directory named app_api. In this folder, create two
subfolders: controllers and routes. These subfolders will serve the same purpose as the matching
folders in the app_server tree. Additionally, move the models folder from app_server to app_api.
Creating the Mongoose Schema and Database Access Code
The next step in this process is to create an initial controller that you can use to extract trip information
from the travlr database in MongoDB. Once you have built the controller and added the necessary
routes to the application, you can perform preliminary testing and refactor the website to pull data from
the database instead of the JSON file.

1. Create a file named trips.js in the controllers folder beneath app_api. This file will be where you
create the first methods that will integrate with MongoDB to retrieve data for the application.
Build a single controller that will retrieve a list of all available trips. Starting with one controller,
add more controllers to make the debugging process easier.
2. To activate a controller, you must add a route to the controller so the web server knows how to
process a specific request. Add a router for the API work. You will simplify how you approach the
routing because there are likely to be more API endpoints to enable. Create an index.js file in
the routes folder beneath app_api.
3. Now that you have the routes, adjust the app.js to pull the necessary items into the application.
You must repoint the db module because you moved it underneath app_api. Define the
apiRouter variable and wire it up to the /api path.
4. Now that the route is wired up in the app, you should run the web server and test the app. You
could test the app by going to http://localhost:3000/api/trips in your web browser. However,
this is a good opportunity to use Postman to review the API transaction. Open Postman and
select continue with the lightweight API client. Enter your URL and click Send to continue.

You should be able to see and scroll through the JSON output of the Mongoose call. The output should
match the data that you used to seed the database.
5. Now that the controller and route are accessing the database, you can add a route to the API.
Re-open the trips.js file in the app_api/controllers directory. Duplicate and modify the tripsList
endpoint to create an endpoint that will take a single parameter and use that as a filter to select
a single trip from the database. In this exercise, the code field will be your parameter.

Notice that there is a very small change to pull in the tripCode parameter from the API endpoint.
6. Before you can use the new controller, make a small edit to the index.js file in the
app_api/routes folder. Add a route to take advantage of the parameterized controller.
7. Now that you have made changes, recycle the application and test it to see that the new
instance of the controller returns a single record. Run the test in Postman by adding one of the
trip codes to the URL string for the call to the API endpoint.
8. Another method to test your API for GET methods is to enter the URL directly into your browser.
This method is good for quick testing, but it is more difficult to manage when running a lot of
tests. For this reason, you should use Postman for API testing. Here is an example with the
/api/trips endpoint and the /api/trips/:tripCode endpoint.

Here is an example with a filtered API call.


9. There is one more area that should be modified to help you use the new API. You can adjust the
travel.hbs template to change the HREF target to use the API and further show that the filtered
API call can be successful.
When testing in your browser, you can see that selecting the image for each travel location will show
the JSON data for the trip.

Clicking on the image brings up the JSON for the trip record.

While this is not an example of what you would normally do in a production system, it is a good example
of what is possible with the API methodology. You can also test your environment during the build
process.
Modify Public Website to Use API Endpoints
In the previous section, you ran across another item that needs to be refactored. The rendered view still
uses static JSON from a file. You must update this to use the new API endpoints. Review Chapter 7 of
your textbook for guidelines to wire up the view to the new API endpoints to pull data from the
database.

1. Determine how to pull the data in from the APIs. Previously, you would have used the request
Node module. But that module has been deprecated and is no longer being maintained. The
Node module’s use in a production environment should be eliminated. In this case, you will use
the fetch API that is now built into Node.js. To use this method, you will need to modify the
controller in app_server/controllers/travel.js. There are several ways to reach this outcome,
but you will use a method that makes minimal changes to the original controller. The original
controller from the GitHub archive is shown here:

2. Because the data was originally generated from the JSON seed file, you must add some
information to attach to the API endpoint. This process will include the URL and the options you
need to set on the connection. These options include deciding which HTML verb to use (GET)
and which headers need to be identified. Start by creating a variable for the API endpoint and
one for the list of options.

const tripsEndpoint = 'http://localhost:3000/api/trips';


const options = {
method: ‘GET’,
headers: {
‘Accept’: ‘application/json’
}
}
3. Comment out the two lines that you used to read the data in from the seed file.

// var fs = require('fs');
// var trips = JSON.parse(fs.readFileSync('./data/trips.json','utf8'));

4. Replace the definition of the travel object with an asynchronous (async) function. This step is
necessary as client interactions with an API endpoint are not naturally synchronous. By defining
a function as async, you can use the await keyword that synchronizes the communication and
simplifies interaction with the endpoint.

Notice in the above screenshot the three additional logging statements that have been commented out.
These statements allow you to experiment with the function and the order in which things occur in the
Node.js environment. If you remove the async and await tokens, the app may not work as expected. All
the data will be collected but not necessarily in the expected order.
The console.log capability is a good way to provide some debugging information when determining what
is happening with your code. This information will be displayed in the PowerShell window where you
start your application.

The fetch method has three major components. First is the main portion of the execution.

fetch(URL, Options)

This part is the initial configuration of the routine. You can see how to wire up the URL and options in
the above section. The second part is the .then clause for the method. You can chain multiple clauses,
and they will be executed in order. You will use two .then clauses here:

.then(res => res.json())


.then(json => {
// console.log(json);
res.render('travel', {title: 'Travlr Getaways', trips: json});
})

The first of these clauses takes the result from the fetch command and provides the output as JSON. The
second of these clauses takes the JSON object from the previous clause and passes it to the render
method. Note: The trips token at the end of the render line used to be the output of reading the data
file. The trips token has been changed and replaced as a key-value pair where trips: is the key and json is
the collection of values retrieved from the API.

The third part of the fetch command is the .catch clause that you can use to tag any errors in the
communication with the API. You add the .catch clause here:

.catch(err => res.status(500).send(e.message));


5. Restarting your web server now will allow you to test the application. You should see that the
/travel page is rendered properly.
6. You need to adjust one more item in the controller. Otherwise, additional error conditions may
occur when pulling data from the database through the API. The first is a condition where the
response does not contain any data. Specifically, the response is not an array of JSON objects.
The second is a condition where the response is an array of JSON objects, but the array is of
length zero. In this case, no data is in the database to support the call. In these cases, you must
add some tests and appropriate messaging.

7. Optional: You can repeat the process shown above to create methods specific to travelDetails.
Finalizing Module Five

1. Now that you have completed Module Five, go back to Git and add everything to tracking. Start
by checking the status of what has changed by using the git status command.

2. Add all changes into tracking by using the git add . command.

3. Commit the changes by using git commit -m ‘Module 5 completed baseline’.

4. Push the changes back to GitHub for safekeeping by using git push --set-upstream origin
module5.

You might also like