make request to jsonplaceholder in typescript

To make HTTP requests to the JSONPlaceholder API in TypeScript, follow these steps:

  1. Install the axios library by running npm install axios or yarn add axios.

  2. Import axios into your TypeScript file:

    index.ts
    import axios from "axios";
    
    27 chars
    2 lines
  3. Define the type of your data. Assuming you're making a GET request to the /todos endpoint, you can define the type like this:

    index.ts
    type Todo = {
      id: number;
      userId: number;
      title: string;
      completed: boolean;
    };
    
    88 chars
    7 lines
  4. Make the request using the axios.get() function:

    index.ts
    const url = "https://jsonplaceholder.typicode.com/todos";
    axios.get<Todo[]>(url).then(response => {
      const todos = response.data;
      console.log(todos);
    });
    
    157 chars
    6 lines

In this example, we're making a GET request to the /todos endpoint and expecting an array of Todo objects as a response. We then log the todos array to the console.

You can also make other types of requests (POST, PUT, DELETE) using the relevant axios functions (axios.post(), axios.put(), axios.delete()).

gistlibby LogSnag