Making Http requests with Axios in TypeScript

avatar

Borislav Hadzhiev

Thu Feb 17 20224 min read

banner

Photo by Zack Minor

Table of Contents #

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

Making Http GET requests with Axios in TypeScript #

Make sure to install axios before using the code snippets in this article.

You can install axios by opening your terminal in the root directly of your project with the npm install axios command.

shell
npm install axios
Axios includes TypeScript definitions, so we don't have to install them separately.

Here is an example of an HTTP GET request using axios in TypeScript.

index.ts
import axios from 'axios'; type User = { id: number; email: string; first_name: string; }; type GetUsersResponse = { data: User[]; }; async function getUsers() { try { // 👇️ const data: GetUsersResponse const { data, status } = await axios.get<GetUsersResponse>( 'https://reqres.in/api/users', { headers: { Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); // 👇️ "response status is: 200" console.log('response status is: ', status); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } getUsers();

We defined the type for the response we expect from the server and provided it when using the axios.get method.

As you can see the first parameter we passed to the axios.get() method is the url.

The second parameter is a request config object and is not required.

I only included the second parameter, because might be making HTTP GET requests to an API that requires authorization, so you might need to set an Authorization header.

If you need to check the response schema, look at this section of the axios GitHub repository.

We destructured the data property from the axios response schema.

The data property is the response that was provided by the server.

Another property you might need to use from the response object is status, which represents the status code from the server response, e.g. 200 or 404.

Axios includes a type guard for errors, which we used in our catch method.

If the error is an axios error, we can safely use the message property to get the error message, otherwise the error is typed as unknown and we have to manually check its type before accessing any properties.

What you might have noticed is that axios automatically parses the JSON from the response, as opposed to the built-in fetch() method.

Making Http POST requests with Axios in TypeScript #

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

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

index.ts
import axios from 'axios'; type CreateUserResponse = { name: string; job: string; id: string; createdAt: string; }; async function createUser() { try { // 👇️ const data: CreateUserResponse const { data } = await axios.post<CreateUserResponse>( 'https://reqres.in/api/users', { name: 'John Smith', job: 'manager' }, { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); // 👇️ error: AxiosError<any, any> return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } createUser();

We used the axios.post method to make an HTTP POST request.

We passed the type of the expected response as a generic to the axios.post() method.

Notice that we passed the request body as the second parameter to the post() method.

We don't have to pass the request body to the JSON.stringify() method as axios automatically takes care of this.

For demonstration purposes, we also included the third parameter which is the configuration for the HTTP request.

We included an object containing the request headers. If your remote API requires authentication, you might need to set an Authorization header that points to a json web token.

You can look at the other possible values in the request config by visiting the axios GitHub repository.

Making Http PATCH requests with Axios in TypeScript #

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

index.ts
import axios from 'axios'; type UpdateUserResponse = { name: string; job: string; updatedAt: string; }; async function updateUser() { try { // 👇️ const data: UpdateUserResponse const { data } = await axios.patch<UpdateUserResponse>( 'https://reqres.in/api/users/2', { name: 'John Smith', job: 'manager' }, { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); // 👇️ error: AxiosError<any, any> return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } updateUser();

The axios.patch method is very similar to axios.post - it takes the exact same 3 parameters:

  1. The url (the server url that will be used for the request)
  2. The request body
  3. The request config object

Making Http PUT requests with Axios in TypeScript #

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

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

index.ts
import axios from 'axios'; type UpdateUserResponse = { name: string; job: string; updatedAt: string; }; async function updateUser() { try { // 👇️ const data: UpdateUserResponse const { data } = await axios.put<UpdateUserResponse>( 'https://reqres.in/api/users/2', { name: 'John Smith', job: 'manager' }, { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); // 👇️ error: AxiosError<any, any> 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 - instead of using axios.patch, we are now using axios.put.

Making Http DELETE requests with Axios in TypeScript #

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

index.ts
import axios from 'axios'; type DeleteUserResponse = ''; async function deleteUser() { try { // 👇️ const data: UpdateUserResponse const { data, status } = await axios.delete<DeleteUserResponse>( 'https://reqres.in/api/users/2', { headers: { Accept: 'application/json', }, }, ); console.log('response is: ', data); // 👇️ response status is: 204 console.log('response status is: ', status); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); // 👇️ error: AxiosError<any, any> return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } deleteUser();

The API I'm using in the examples sends an empty string as a response for an HTTP delete request.

Most APIs return a 204 "No Content" status when an HTTP Delete request is made.

The 2 parameters the axios.delete method takes are the url and the request config object.

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