CS 465 Module Five Full Stack Guide
CS 465 Module Five Full Stack Guide
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.
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.
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.
// 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:
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:
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.
4. Push the changes back to GitHub for safekeeping by using git push --set-upstream origin
module5.