Week 9 - Networking and APIs

Introduction to Networking

Client Server Model

TCP/IP Protocol

HTTP Protocol

URL Format

Web APIs

API Testing Tools

Using APIs

AI Responsible Use

Practice

Assignment

Back to core program

Week 9 Assignment

Preparation

After forking and cloning the assignment repository (see Submission below), run the following command to install the required Node.js dependencies:

npm install

Task 1 - curl commands

In this task you will practice reading API documentation and using curl. The API reference you need is in the GUIDE.md file. Read it carefully and construct your own curl requests from the endpoint details.

Before you start, open a terminal in the repository root and start the server with npm start. Keep it running while you work.

Create your scripts inside the task-1 folder and run each script with bash after you finish it.

  1. Create a post.sh bash script. It must send a POST request with curl to create a new user. Use these values in the JSON body:

    Field Value
    name (string) John Doe
    email (string) [email protected]
    role (string) user
    active (boolean) true
    department (string) Engineering

    Run the script. Record the id from the response. You will need it in the next steps.

  2. The email address from the previous step mistakenly included an extra dot between first and last name. We will correct it here. Create a patch.sh bash script. It must send a curl PATCH request to update the email address for the user you just created. Fix the email by removing the extra dot, changing it to [email protected]. Note that in general, a PATCH request should include only the fields you are updating. In our case this is the email field only.

  3. Create a get.sh script. It must send a curl GET request to fetch the user by id. Verify the response contains the updated email.

  4. Create a delete.sh script. It must send a curl DELETE request for the same id to remove the user.

  5. Re-run the get.sh script. The response should now be "User not found".

When you are satisfied with the results of your bash scripts, you can verify that Task 1 will successfully pass all tests performed by the auto-grading facility when you submit your pull request. To do so, open a second terminal window and type the command:

npm run test:task-1

If all is well you see output similar to this:

> [email protected] test:task-1
> vitest --run tests/task-1.test.js

 RUN  v4.0.18 /Volumes/Crucial2TB/xdev/hackyourfuture/core-assignment-week-9

 ✓ tests/task-1.test.js (9 tests) 149ms
   ✓ curl scripts (9)
     ✓ post.sh: Script exists 0ms
     ✓ post.sh: Create user John Doe 74ms
     ✓ patch.sh: Script exists 0ms
     ✓ patch.sh: Correct the email address 20ms
     ✓ get.sh: Script exists 0ms
     ✓ get.sh: Retrieve user John Doe details 18ms
     ✓ delete.sh: Script exists 0ms
     ✓ delete.sh: Delete user John Doe 19ms
     ✓ get.sh: Verify user John Doe has been deleted 17ms

 Test Files  1 passed (1)
      Tests  9 passed (9)
   Start at  16:35:08
   Duration  233ms (transform 9ms, setup 0ms, import 14ms, tests 149ms, environment 0ms)

When you have completed all steps, stop the server with Ctrl-C in the terminal window where you started the server.

Task 2 - Nobel Prizes Web App

For this task you will be using a pre-made Web application. Your job will be to complete the file services.js in the task-2 folder that is responsible for fetching the data required for the application. The application uses the NobelPrize API to display a list of awarded Nobel Prizes, optionally filtered by Nobel Prize category and award year. Here is what it looks like:

SCR-20260204-pfbd.png

The list is paginated and there are buttons at the bottom to page through the list:

SCR-20260204-pfhp.png

The API documentation is provided by the Nobel Prize organization in the Open API format. This interactive, standardized format enables you to directly try the API from the documentation website. The relevant Open API documentation for this task can be found here:

The only endpoint we will use is GET /nobelPrizes. The pre-made application features two dropdown boxes, one for selecting the Nobel Prize category and another one for selecting the Nobel Prize year. The dropdowns default to All, which means that no filtering will be done on the relevant criterion.

The provided services.js file that you need to complete looks like this:

import { fetchData } from './fetcher.js';

const API_BASE_URL = '<https://api.nobelprize.org/2.1>';

/**
 * Fetch Nobel Prizes with optional filters
 * @param {Object} filters - Filter options
 * @param {string} filters.year - Year to filter by (optional)
 * @param {string} filters.category - Category code to filter by (optional)
 * @param {number} filters.offset - Pagination offset (default: 0)
 * @param {number} filters.limit - Number of results per page (default: 10)
 * @param {Function} onSuccess - Callback for successful fetch
 * @param {Function} onError - Callback for fetch errors
 */
export function fetchNobelPrizes(filters = {}, onSuccess, onError) {
  let url = ''; // TODO Construct the full URL with query parameters;

  fetchData(url, onSuccess, onError);
}

The function fetchNobelPrizes() is called with three arguments:

  1. A filters JavaScript object containing filter properties as set up by the web UI, depending on the state of the dropdowns and the pagination. This object is detailed later.
  2. An onSuccess callback function.
  3. An onError callback function.

Internally, the fetchNobelPrizes() function calls the imported fetchData() function, which takes a url as its first parameter, and the onSuccess and onErrror callbacks that are passed on to fetchData() unmodified.

For this exercise, you can consider the fetchData() function as a black box, i.e. you do not need to consider how it is implemented. The only thing you need to know is how to call it. In fact, the only thing that you need to do is to construct the full url that is needed to fetch the data given the filter values passed in the filters object. It may contain the following properties:

Field Value
year (string, optional) The Nobel Prize year or not present if All is selected.
category (string, optional) The Nobel Prize category or not present if All is selected.
offset (number) An offset that indicates from which location in the list the current page starts. This offset is managed by the pagination buttons.
limit (number) The number of items per page. This is a fixed number, set by the Web UI.

There is an additional query parameter that is not passed in the filters object, but that you nevertheless need to include in the url. This is the sort property, which should be set to desc (sort descending by year).

To summarize, your task is to complete the url that is passed to fetchData() from the filters object passed as the first parameter to the fetchNobelPrizes() function. In order to do so you must read the Open API documentation for the GET /nobelPrizes endpoint, perhaps try it out online and then implement it in services.js.

Running the application

A convenient way to run web application inside a project folder in VS Code is to use the Live Server VS Code extension. If not installed already, you can install it by typing “Live Server” in the extension explore in VS Code. Find the one authored by Ritwick Dey and click Install.

Alternatively, you can also install it from the VS Code Marketplace at this link: https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

To run the finished web app in the browser, right-click the index.html file and select Open with Live Server from context menu.

When developing web application like the current one it is recommended to open the Developer Tools from the browser so that you can inspect the console for possible error messages. Check the table below for the short-cut key combination for your computer’s operation system.

Operating System Shortcut Combination
Windows F12 or Ctrl + Shift + I
macOS Cmd + Option + I
Linux F12 or Ctrl + Shift + I

The pre-made web app will display the URL and the returned data in the Develop Tools console tab, as shown in this example (the exact URL has been hidden to not give away the solution for this task):

SCR-20260204-tdtn-2.png

Try and change the Category and Year dropdown and verify that the app responds appropriately. Try the pagination buttons at the bottom of the page too.

Running the Unit Tests

The unit tests for task 2 checks whether the URL is correctly constructed for various combinations of property values in the filters object. To run the unit test, use this command:

npm run test:task-2

Submission

The assignment repository can be found in https://github.com/HackYourAssignment/ with the name cXX-core-week-## (Replace XX with your cohort number and ## with the week number)

Follow the Assignment submission guide to learn how to submit the assignment