Lecture Notes Of Day 17: Working with APIs in JavaScript

Rashmi Mishra
0

 

Lecture Notes Of Day 17: Working with APIs in JavaScript

Objective:

To learn how to make HTTP requests to interact with APIs using JavaScript, handle responses, and parse JSON data returned from an API.

Topics Covered:

1.  Using fetch() to Make API Requests

2.  Handling API Responses

3.  Parsing JSON Data from API Responses


1. Introduction to APIs

APIs (Application Programming Interfaces) allow one application to interact with another. APIs expose a set of endpoints (URLs) that allow clients (such as your JavaScript code) to send requests and receive data in return. The data is usually returned in formats like JSON or XML.

Key Concepts:

  • Request: The action you make to the server (GET, POST, PUT, DELETE).
  • Response: The data or result sent back by the server.

JavaScript makes it easy to work with APIs, particularly through methods like fetch().


2. Using fetch() to Make API Requests

fetch() is a JavaScript function that allows you to make HTTP requests to a server. It's modern and flexible, and it returns a Promise that resolves to the response of the request.

Syntax of fetch():

javascript

Copy code

fetch(url, options)

  • url: The endpoint (URL) where the API request is sent.
  • options: An optional object where you can specify HTTP methods (like GET, POST, etc.), headers, body data, etc.

By default, fetch() uses the GET method to retrieve data.

Basic Example - GET Request:

javascript

Copy code

fetch('https://api.example.com/data')

  .then(response => response.json()) // Parsing the response as JSON

  .then(data => console.log(data)) // Use the fetched data

  .catch(error => console.error('Error:', error)); // Handle any errors

In this example:

  • fetch('https://api.example.com/data'): Sends a GET request to the specified URL.
  • .then(response => response.json()): The response is returned as a Promise. We call .json() to parse the data from JSON into a JavaScript object.
  • .then(data => console.log(data)): The parsed data is logged to the console.
  • .catch(error => console.error('Error:', error)): If an error occurs (e.g., network failure), it will be caught and logged.

3. Handling API Responses

When working with APIs, it’s important to understand the structure of the response returned from the server. Typically, API responses include:

  • Status Code: Indicates the success or failure of the request (e.g., 200 for success, 404 for not found).
  • Headers: Metadata about the response, such as content type, length, etc.
  • Body: The actual data returned from the server, usually in JSON or XML format.

Here’s how you can handle a response effectively:

Checking Response Status:

javascript

Copy code

fetch('https://api.example.com/data')

  .then(response => {

    if (!response.ok) {

      throw new Error('Network response was not ok');

    }

    return response.json();

  })

  .then(data => console.log(data))

  .catch(error => console.error('There has been a problem with your fetch operation:', error));

In this example:

  • response.ok: This is a boolean property. If the status code is between 200-299, it’s considered a successful response.
  • If the status code indicates failure (like 404 or 500), we throw an error.

4. Parsing JSON Data from API Responses

JSON (JavaScript Object Notation) is a lightweight data format that is easy for both humans to read and machines to parse. Most modern APIs return data in JSON format.

When you make a request to an API, you’ll typically need to parse the response data from JSON into a usable JavaScript object. This is done using the .json() method of the Response object.

Example of JSON Parsing:

javascript

Copy code

fetch('https://jsonplaceholder.typicode.com/posts')

  .then(response => response.json()) // Parse the response as JSON

  .then(data => {

    data.forEach(post => {

      console.log('Title:', post.title); // Output the title of each post

    });

  })

  .catch(error => console.error('Error:', error));

In this example:

  • The API at 'https://jsonplaceholder.typicode.com/posts' returns an array of posts in JSON format.
  • response.json() parses the JSON string into a JavaScript array.
  • We then loop through the array and log the titles of each post.

Understanding the JSON Structure:

Here’s an example of what the JSON data might look like:

json

Copy code

[

  {

    "userId": 1,

    "id": 1,

    "title": "Sample Post Title",

    "body": "This is the content of the post."

  },

  {

    "userId": 1,

    "id": 2,

    "title": "Another Post Title",

    "body": "This is another content of the post."

  }

]

The response is an array of objects, and each object represents a post with properties like userId, id, title, and body.


5. Making Other Types of HTTP Requests

While GET is the most commonly used HTTP method for retrieving data, you might also need to send data to the server. This is done using methods like POST, PUT, and DELETE.

Example of POST Request (Sending Data to an API):

javascript

Copy code

fetch('https://jsonplaceholder.typicode.com/posts', {

  method: 'POST',

  headers: {

    'Content-Type': 'application/json',

  },

  body: JSON.stringify({

    title: 'New Post',

    body: 'This is a new post content.',

    userId: 1,

  })

})

  .then(response => response.json())

  .then(data => console.log('Data posted:', data))

  .catch(error => console.error('Error:', error));

In this example:

  • The method: 'POST' specifies that we are sending data to the server.
  • The headers indicate that we are sending JSON data.
  • The body contains the data that will be sent to the server, and JSON.stringify() converts the JavaScript object into a JSON string.

Example of DELETE Request (Deleting Data from an API):

javascript

Copy code

fetch('https://jsonplaceholder.typicode.com/posts/1', {

  method: 'DELETE',

})

  .then(response => {

    if (response.ok) {

      console.log('Post deleted');

    } else {

      console.error('Failed to delete post');

    }

  })

  .catch(error => console.error('Error:', error));

In this example:

  • The method: 'DELETE' specifies that we want to delete the post with ID 1.
  • If the delete request is successful, we log a success message.

6. Handling Errors

Errors can occur while making API requests, such as:

  • Network errors (server unavailable, no internet connection, etc.)
  • API-specific errors (invalid endpoint, missing parameters, etc.)

To handle errors, always use .catch() after your .then() chain to handle any unexpected issues.

Example:

javascript

Copy code

fetch('https://api.example.com/data')

  .then(response => {

    if (!response.ok) {

      throw new Error('API error: ' + response.statusText);

    }

    return response.json();

  })

  .then(data => console.log(data))

  .catch(error => console.error('Fetch error:', error));


7. Conclusion

By using fetch() and understanding how to make HTTP requests, handle responses, and parse JSON data, you can interact with a wide variety of web APIs in JavaScript. These APIs enable you to work with dynamic data, allowing you to create more interactive and data-driven web applications.

Key points:

  • fetch() allows you to make HTTP requests.
  • Handling responses properly is crucial, especially for error handling.
  • Parsing JSON is necessary when working with API responses that return JSON data.

In the next lessons, you’ll dive deeper into more advanced features of working with APIs, such as error handling, authentication, and working with asynchronous data fetching.

Post a Comment

0Comments

Post a Comment (0)