Working with Web APIs

Learn how to work with web APIs while using the CLI.

We'll cover the following

An API, or Application Programming Interface, lets developers interface with An API, or Application Programming Interface, lets developers interface with data without accessing the data directly. Web APIs let us do this by making requests to servers. APIs can let us see current weather conditions, stock prices, sports scores, social media feeds, and pretty much any data we’re looking to consume.

If we’re writing software that interfaces with a third-party web API, or if we’re developing our own, we can use cURL to explore and test that API. We can set headers, define request types, and send data payloads.

To explore this, we need an API we can work with. Instead of using a live API for testing, we use json-server, a Node.js package that provides an API for these types of situations. Let’s set it up inside of the Ubuntu virtual machine.

Setting up Node.js

First, we use curl to download an installation script from NodeSource that adds their repository to our system and updates the list of available packages:

cat google.html
$ curl -L -O

Now, we execute the installation script and install the nodejs package:

$ sudo bash ./setup_11.x
$ sudo apt install nodejs

This installs Node.js, along with npm, a command for installing Node.js libraries and programs, and npx, a command that downloads and then executes applications.

We’ve already done this on our end, so you don’t need to worry about this.

Running the server

Now, we create a JSON file in our home directory called data.json with the following content:

   "notes": [
               { "id": 1, "title": "Hello" } 

The json-server command will use this as its data and turn it into a REST API we can query.

With the file created, we use the npx command to run json-server and tell it to watch the data.json file for changes:

$ npx json-server -w ~/data.json

We’re running this with the nohup command so that the server runs in the background and we don’t have to initiate a new terminal session.

We make a request to http://localhost:3000/notes, and we see the notes we created in the data.json file appear on the screen:

$ curl http://localhost:3000/notes

Run the terminal below to execute this command:

Get hands-on with 1200+ tech skills courses.