Using Query Parameters

Lesson Overview

Welcome to our lesson on using query parameters with axios and working with REST! In this lesson, we will explore how to use query parameters with Node.js's axios library and extract data from REST APIs. By the end of this lesson, you will have solidified your knowledge of data retrieval and will be able to effectively use query parameters and REST APIs to fetch data, laying the foundation for your future web-scraping projects.

Query Parameters and Node.js's axios Library

Let's first talk about what query parameters are. Query parameters, also known as query strings, are used to send data to the server in the form of key-value pairs. They are attached to the end of a URL after a ? character and separated by & for multiple parameters. For example, if you have ever filtered a search result on a website and noticed your URL change to something like http://website.com/search?param1=value1&param2=value2, those are query parameters in action!

Node.js's axios library offers a simple way to pass those query parameters. The axios.get() method accepts a parameter, params, that can be used to specify these. Let's illustrate this in the code we have:

JavaScript
const axios = require('axios');

const urlActionApi = 'https://en.wikipedia.org/w/api.php';
const paramsActionApi = {
    action: 'query',
    prop: 'info',
    titles: 'Earth',
    format: 'json'
};

const responseActionApi = await axios.get(urlActionApi, { params: paramsActionApi });

Here, paramsActionApi is an object of key-value pairs, which specify the parameters to be included in the query string. axios.get() then constructs the URL with these parameters.

When we fetch data from the server, it often comes back in JSON (JavaScript Object Notation) format, which is a lightweight data-interchange format that is easy to read and write. With axios, the JSON response is automatically parsed and available through the response.data property:

JavaScript
try {
    const responseActionApi = await axios.get(urlActionApi, { params: paramsActionApi });
    console.log("Content from Wikipedia's action API fetched successfully!");
    console.log(responseActionApi.data);
} catch (error) {
    console.log("Failed to fetch content from Wikipedia's action API.");
}

Introduction to REST APIs

REST APIs are a type of web service that allows communication between different systems over the internet. They are based on the principles of REST, which stands for Representational State Transfer. REST APIs use standard HTTP methods like GET, POST, PUT, DELETE, etc., to perform operations on the server. REST APIs return data in JSON format, which can be easily parsed using Node.js's axios library.

REST APIs usually support CRUD (Create, Retrieve, Update, Delete) operations. For example, you can use a REST API to fetch data from a server, update data, or delete data. REST APIs are stateless, meaning each request from a client to the server must contain all the information needed to understand the request. This makes REST APIs easy to use and understand.

Here are some common HTTP methods used in REST APIs:

  • GET: Used to retrieve data from the server.
  • POST: Used to send data to the server to create a new resource.
  • PUT: Used to send data to the server to update an existing resource.
  • DELETE: Used to delete a resource on the server.

In the next section, we will explore how to interact with REST APIs using Node.js's axios library.

Working with REST using Node.js's axios Library

The Node.js axios library simplifies the process of working with REST APIs. To send a GET request and fetch data from a REST API, we use the axios.get() method. Let's look at an example where we interact with a REST API using query parameters:

JavaScript
// Example with JSONPlaceholder API using query parameters
const urlRestApi = 'https://jsonplaceholder.typicode.com/posts';
const restParams = {
    userId: 1,
    _limit: 5
};

const responseRestApi = await axios.get(urlRestApi, { params: restParams });

In this example, we're fetching posts from the JSONPlaceholder API with query parameters to filter results by userId and limit the number of results to 5. The axios.get() method automatically constructs the URL with these parameters.

We can then access the response JSON data through the data property:

JavaScript
try {
    const responseRestApi = await axios.get(urlRestApi, { params: restParams });
    console.log("Content from REST API fetched successfully!");
    console.log(responseRestApi.data);
} catch (error) {
    console.log("Failed to fetch content from REST API.");
}

The output of the above code will be an array of post objects filtered by the specified parameters:

Content from REST API fetched successfully!
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur..."
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit..."
  },
  // ... up to 5 posts for userId: 1
]

This output shows the REST API's response for fetching posts filtered by user ID 1 and limited to 5 results. Each post object contains an ID, title, body, and user ID.

Let's explore another example where we delete a resource using the DELETE method:

JavaScript
// DELETE request to delete a resource using JSONPlaceholder API
const urlDeleteApi = 'https://jsonplaceholder.typicode.com/posts/1';
const responseDeleteApi = await axios.delete(urlDeleteApi);

console.log(responseDeleteApi.status); // Output: 200

In this example, we are using the axios.delete() method to delete the resource with ID 1 from the JSONPlaceholder API. The response will indicate whether the deletion was successful or not. In this case, the status code 200 indicates that the deletion was successful.

Lesson Summary

In this lesson, we covered how to use Node.js's axios library to efficiently work with query parameters and fetch data from REST APIs. These skills are crucial when you need to retrieve data from the web for analysis or web-scraping projects.

Now that we've walked through how to structure requests and handle the responses, it's time to apply these skills. In the following practice exercises, you will be given opportunities to work with different APIs and request configurations, which will strengthen your understanding of these topics. Remember, practical application is key to accelerating your learning journey. So let's get started!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal