DEV Community

Cover image for How To Use API
christopher
christopher

Posted on

How To Use API

In this article, we will be creating a news website with just API. So Creating a news website with API integration involves some steps, including setting up the HTML structure, styling with CSS, and using JavaScript to fetch and display news articles. Below is a step example of how you can create a basic news website using the NewsAPI.

Please note that you need to sign up for a NewsAPI and get an API key for this to work

in our HTML file let us create a container named news-container

**<div id="news-container"></div>**

Next, let's obtain our API key and make an API call.

you've already obtained the key; now you're making the API call.

//The URL of the API you want to fetch data from
const apiKey = 'YOUR_API_KEY';
const apiUrl = 'https://newsapi.org/v2/top-headlines';

const params = {
  country: 'us',
  apiKey: apiKey,
};
data';

//Using fetch to make a GET request
fetch(apiUrl)
  .then(response => {
    //Check if the request was successful (status code 200)
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    //Parse the response JSON and return it as a Promise
    return response.json();
  })
  .then(data => {
    //Handle the data obtained from the API
    console.log(data);
  })
  .catch(error => {
    //Handle any errors that occurred during the fetch
    console.error('Error fetching data:', error.message);
  });
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. URL:
    • Define the URL of the API you want to fetch data from.
  2. Fetch Call:
    • Use the fetch function, passing in the URL as an argument.
    • The fetch function returns a Promise that resolves to the Response to that request.
  3. Check for Errors:
    • Inside the first then block, check if the response was successful (status code 200). If not, throw an error.
  4. Parse Response:
    • If the response is successful, use the json method on the response to parse the JSON content. This method also returns a Promise.
  5. Handle Data:
    • In the second then block, handle the parsed data.
  6. Handle Errors:
    • Use the catch block to handle any errors that might occur during the fetch operation.

This should give you a good starting point for understanding and using the fetch API in your web development projects.

Top comments (0)