get api in typescript

To use an API in TypeScript, you can make use of the popular axios library. Here's an example of how to use it:

index.ts
import axios from 'axios';

interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

const apiUrl = 'https://jsonplaceholder.typicode.com/todos';

async function fetchTodos(): Promise<Todo[]> {
  const response = await axios.get(apiUrl);
  return response.data;
}

fetchTodos().then(todos => {
  console.log(todos);
});
336 chars
19 lines

In this example, we have first defined an interface for the Todo object. We then make use of axios to make an HTTP GET request to the API endpoint.

We await the response and then return the response's data as an array of Todo objects. This function returns a Promise of an array of Todo objects.

Finally, we call the fetchTodos function and log the returned todos to the console.

Note that in order to use axios, you must first install it via npm or yarn:

index.ts
npm install axios
18 chars
2 lines

or

index.ts
yarn add axios
15 chars
2 lines

gistlibby LogSnag