Web APIs

What is a Web API?

A Web API (Application Programming Interface) is a set of rules and tools that allows different software applications to communicate with each other over the internet. In the context of web development, it often refers to APIs that provide data and functionality to be used by web applications.

In simpler terms, a Web API allows your application to make requests to a server and receive data or perform actions without understanding the internal workings of that server. It acts as an intermediary, providing a standardized way for different systems to interact.

Example using React and Superagent npm package:

Here's a simple example using the Superagent npm package to make an HTTP request to a public API. In this example, we'll use the JSONPlaceholder API, which is a fake online REST API for testing and prototyping.

Take an look at this API and see what is returned: https://jsonplaceholder.typicode.com/todos/1. We can use this data in our application.

  1. Install Superagent:

    npm install superagent
  2. Create a React component with an asynchronous function:

    // Import necessary libraries
    import React, { useState, useEffect } from 'react'
    import request from 'superagent'
    // Define the API endpoint (mock API URL)
    const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';
    // Define TypeScript interface for the data structure
    interface Data {
    userId: number;
    id: number;
    title: string;
    completed: boolean;
    }
    // Define the component
    function MyComponent() {
    const [data, setData] = useState(null as Data | null)
    // Define an asynchronous function to fetch data
    const fetchData = async () => {
    try {
    // Make a GET request to the JSONPlaceholder API
    const response = await request.get(apiUrl)
    // Extract and set the data from the response
    setData(response.body)
    } catch (error: unknown) {
    if (err instanceof Error){
    console.error('Error fetching data:', error.message)
    }
    else {
    console.error('Error fetching data: unknown')
    }
    }
    };
    // Use the useEffect hook to call the asynchronous function on component mount
    useEffect(() => {
    fetchData();
    }, []) // Empty dependency array ensures the effect runs once on mount
    // Render the component
    return (
    <div>
    <h1>Web API Example with React and Superagent</h1>
    {/* Ternary operator to display either retrieved data or `Loading...` */}
    {data ? (
    <div>
    <p>ID: {data.id}</p>
    <p>Title: {data.title}</p>
    </div>
    ) : (
    <p>Loading...</p>
    )}
    </div>
    )
    }
    export default MyComponent

This example uses the Superagent library to make an asynchronous GET request to the JSONPlaceholder API. The useEffect hook in React is used for handling side effects in functional components. In this example, we use useEffect to ensure that the fetchData function is called when the component mounts.

The second argument of useEffect is an array of dependencies. By providing an empty array `([])``, we indicate that this effect should run only when the component first renders. If the array contained variables, the effect would run whenever any of those variables change.

In this context, we use `useEffect`` to initiate the data-fetching process when the component is first rendered.

This is a simplified example to introduce the concept of making API requests in a React component using the async/await syntax. In a real-world scenario, error handling and more complex state management might be necessary.