Published on

TypeScript: HTTP Requests with Fetch

Table of Contents

Fetching data from an API is a common task in modern web development. With the introduction of the Fetch API, it has become easier to make network requests in JavaScript. TypeScript, on the other hand, adds an extra layer of type safety to JavaScript, making it a preferred language for large scale applications. In this blog post, we will explore how to use the Fetch API in TypeScript with examples.

Setup

First, we need to install the Fetch API polyfill since it is not supported by all browsers.

npm install --save whatwg-fetch

GET

Now that we have Fetch installed, let's start by creating an interface for our API response. Here, we'll be making a GET request to fetch a list of members from an API. Here's what our Member interface looks like:

ts-interface.tsx
interface Member {
  id: number
  fullName: string
  subscriptionID?: string
  createdAt: string
  isActive: boolean
}

Now, let's create a function to make our HTTP request. Here, we'll be using the GET method to fetch our list of members:

ts-get-fnc.tsx
interface Member {
  id: number;
  fullName: string;
  subscriptionID?: number;
  createdAt: Date;
  isActive: boolean;
}
  const fetchMembers = async (): Promise<Member[]> =>
    fetch('https://6414dbc28dade07073ca4f04.mockapi.io/api/v1/members')
      .then((response) => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .then((data) => {
        console.log(data)
        return data as Member[]
      })
      .catch((error) => {
        console.error(error)
        return []
      })

  fetchMembers().then(members => console.log("GET /members finished !") )

In the code above, we're using the fetch method to retrieve our list of members.

POST

ts-post.tsx
  const createMember = async (newMember: Member): Promise<Member> => {
    const requestInit: RequestInit = {
      method: 'POST',
      body: JSON.stringify(newMember),
      headers: {
        'Content-Type': 'application/json',
      },
    }

    return fetch('https://6414dbc28dade07073ca4f04.mockapi.io/api/v1/members', requestInit)
      .then((response) => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .then((data) => {
        console.log(data)
        return data as Member
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  createMember(newMember).then((member) => console.log('POST /members finished !'))

The createMember function accepts an object representing a new member and sends a POST request to create that member on the server. The server should respond with the new member object, which is returned from the function.

That's it! We've successfully made HTTP requests using Fetch and TypeScript.

In conclusion, Fetch is a useful library for making HTTP requests in JavaScript, and using it with TypeScript can make your code more type-safe and easier to maintain. By following the steps outlined in this guide, you can easily make HTTP requests using Fetch and TypeScript in your own projects.