How to Make Http requests in TypeScript

avatar

Borislav Hadzhiev

Thu Feb 17 20225 min read

banner

Photo by Larm Rmah

Table of Contents #

  1. Making Http GET requests in TypeScript
  2. Making Http POST requests in TypeScript
  3. Making Http PATCH requests in TypeScript
  4. Making Http PUT requests in TypeScript
  5. Making Http DELETE requests in TypeScript

Making Http GET requests in TypeScript #

Let's look at examples of how to many Http requests in TypeScript.

If you want to use the axios package to make Http requests in TypeScript, check out my other article - Making Http requests with Axios in TypeScript, as this article uses the built-in fetch method.

At the time of writing you have to install the node-fetch package if you're running your code in Node.js.

Note that you only have to install and import node-fetch if you're running your code in Node.js, as fetch is a built-in method in the browser.

To install the node-fetch package, open your terminal in the root directory of your project and run the following 2 commands.

shell
npm install node-fetch@2.6.1 npm install --save-dev @types/node-fetch@2.x

Here is an example of making an HTTP GET request in TypeScript.

index.ts
// 👇️ only necessary if running in Node.js // (Remove this line if running in the browser) import fetch from 'node-fetch'; type User = { id: number; email: string; first_name: string; }; type GetUsersResponse = { data: User[]; }; async function getUsers() { try { // 👇️ const response: Response const response = await fetch('https://reqres.in/api/users', { method: 'GET', headers: { Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } // 👇️ const result: GetUsersResponse const result = (await response.json()) as GetUsersResponse; console.log('result is: ', JSON.stringify(result, null, 4)); return result; } catch (error) { if (error instanceof Error) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } getUsers();

The first parameter we passed to the fetch() method is the url of the resource.

The second parameter is an options object, where we set an HTTP header and the request method (GET in the example).

Note that a fetch() promise does not reject on HTTP errors, so we have to manually check the response.ok property.

The response.ok property contains a boolean value that states whether the response was successful or not.

If the response was successful, we have to call the json method on the Response interface to parse the JSON from the server into a native JavaScript object.

We used a type assertion to set the type of the parsed response from the server.

In our catch() method, we check if the error is an instance of the Error object, so we can safely access the message property.

Otherwise the error is typed as unknown and we have to manually check its type before accessing any properties.

Making Http POST requests in TypeScript #

Let's look at an example HTTP POST request in TypeScript.

I'll post the entire code snippet and then we'll go over it.

Make sure to remove the fetch import if running in the browser.

index.ts
// 👇️ only necessary if running in Node.js // (Remove this line if running in the browser) import fetch from 'node-fetch'; type CreateUserResponse = { name: string; job: string; id: string; createdAt: string; }; async function createUser() { try { // 👇️ const response: Response const response = await fetch('https://reqres.in/api/users', { method: 'POST', body: JSON.stringify({ name: 'John Smith', job: 'manager', }), headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } // 👇️ const result: CreateUserResponse const result = (await response.json()) as CreateUserResponse; console.log('result is: ', JSON.stringify(result, null, 4)); return result; } catch (error) { if (error instanceof Error) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } createUser();

Notice that we set the http method to POST this time.

We added a request body and used the JSON.stringify() method to convert the object to a JSON string, which we can send over the network.

We also added the Content-Type http header to notify the server that the data in the POST request is a JSON string.

Make sure to always set the Content-Type header to application/json when sending JSON data over the network, as you might get confusing errors if you don't.

Making Http PATCH requests in TypeScript #

Let's look at an example HTTP PATCH request made with fetch in TypeScript.

index.ts
// 👇️ only necessary if running in Node.js // (Remove this line if running in the browser) import fetch from 'node-fetch'; type UpdateUserResponse = { name: string; job: string; updatedAt: string; }; async function updateUser() { try { // 👇️ const response: Response const response = await fetch('https://reqres.in/api/users/2', { method: 'PATCH', body: JSON.stringify({ name: 'John Smith', job: 'manager', }), headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } // 👇️ const result: UpdateUserResponse const result = (await response.json()) as UpdateUserResponse; console.log('result is: ', JSON.stringify(result, null, 4)); return result; } catch (error) { if (error instanceof Error) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } updateUser();

This time we set the method property to PATCH in the options object.

We still have to convert the request body to json, by passing it to the JSON.stringify() method.

Notice that we set the Content-Type header to application/json just like we did when making a POST request.

The last step is to use a type assertion to set the type of the result variable to the expected response type.

Making Http PUT requests in TypeScript #

For completeness sake, let's look at an example HTTP PUT request made with fetch in TypeScript.

index.ts
// 👇️ only necessary if running in Node.js // (Remove this line if running in the browser) import fetch from 'node-fetch'; type UpdateUserResponse = { name: string; job: string; updatedAt: string; }; async function updateUser() { try { // 👇️ const response: Response const response = await fetch('https://reqres.in/api/users/2', { method: 'PUT', body: JSON.stringify({ name: 'John Smith', job: 'manager', }), headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } // 👇️ const result: UpdateUserResponse const result = (await response.json()) as UpdateUserResponse; console.log('result is: ', JSON.stringify(result, null, 4)); return result; } catch (error) { if (error instanceof Error) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } updateUser();

The only thing that changed in the code snippet is - we set the method property in the options object to PUT instead of PATCH.

Making Http DELETE requests in TypeScript #

Let's look at an example HTTP DELETE request made with fetch in TypeScript.

index.ts
// 👇️ only necessary if running in Node.js // (Remove this line if running in the browser) import fetch from 'node-fetch'; async function deleteUser() { try { // 👇️ const response: Response const response = await fetch('https://reqres.in/api/users/2', { method: 'DELETE', headers: { Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } console.log('User deleted successfully'); return 'user deleted successfully'; } catch (error) { if (error instanceof Error) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } deleteUser();

We set the method property to DELETE and removed the body and the Content-Type header, because we aren't sending a request body with a DELETE request.

The API I'm using in the example sends an empty response with a status code of 204 - "No Content".

Note that you shouldn't try to parse an empty response by calling the json() method, because you will get an error: "Unexpected end of JSON input" as the response you're trying to parse has no response body.

Use the search field on my Home Page to filter through my more than 1,000 articles.