If you're a TypeScript developer looking to make HTTP requests in Node.js, you might have come across node-fetch.
In this guide, we'll walk you through the process of using node-fetch in TypeScript, from setting up your project to making basic and advanced HTTP requests.
node-fetch is a popular lightweight library for making HTTP requests from Node.js applications. It provides a simple and consistent API for sending and receiving HTTP/HTTPS requests and responses.
When using node-fetch with TypeScript, developers can take advantage of the strong typing support to catch potential errors at compile time when dealing with APIs, improving code reliability and maintainability.
To set up your project, you'll need to have Node.js and npm installed on your machine. If you don’t, you can download it from here. Then just follow these few simple steps:
To install TypeScript, we can run the command:
sh
npm install -g typescript
Similarly, we can install node-fetch using the following command:
sh
npm install node-fetch
After installing TypeScript, we need to configure it for our project. We can do this by creating a tsconfig.json
file in our project’s root directory. This file contains configuration for TypeScript, such as the target environment, module system, and compilation settings.
You can run this command, and it will create the tsconfig.json
file for you.
sh
tsc --init
Once we have configured TypeScript, we can compile our TypeScript code into JavaScript using the tsc
command.
sh
tsc
To use node-fetch in our TypeScript project, we first need to import it into our code using the require or import statement. For example, we can use this:
ts
const fetch = require('node-fetch')
Or you could also import the node-fetch library like this:
ts
import fetch from 'node-fetch';
Please make sure that you define the type key and set its value to module if you use the import statement to use node-fetch in your project.
Once we have imported node-fetch, we can use it to make HTTP requests. To make a basic HTTP GET request, we can use the fetch() function and pass in the API endpoint URL as a parameter.
Let’s use the Jokes API by API-Ninjas from Rapid API Hub for making the HTTP request.
Please make sure that you have subscribed to the Jokes API.
Now let's create an index.ts
file. We will copy the following code snippet there:
ts
import fetch from 'node-fetch'const url:string = 'https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes';interface IAPIOptions {method: string,headers: {"X-RapidAPI-Key": string,"X-RapidAPI-Host": string}}const options: IAPIOptions = {method: 'GET',headers: {'X-RapidAPI-Key': 'your-rapid-key','X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'}};fetch(url, options).then((res) => res.json()).then((res) => console.log(res)).catch((err: any) => console.error('error:' + err));
Now run tsc
command in your terminal, and it will compile your TypeScript code to JavaScript.
Finally run the following command in your terminal to make the API call:
sh
node index.js
In the previous example, we used the response.json()
method to parse the JSON data returned by the API. We can also use other methods like response.text()
, response.buffer()
, etc., depending on the type of data returned by the server.
Here's an example of using async/await with node-fetch in TypeScript to make a request to the jokes-by-api-ninjas
API:
ts
import fetch from 'node-fetch';const url: string = 'https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes';interface IAPIOptions {method: string;headers: {'X-RapidAPI-Key': string;'X-RapidAPI-Host': string;};}const options: IAPIOptions = {method: 'GET',headers: {'X-RapidAPI-Key': 'your-rapid-key','X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com',},};async function getJokes() {try {const response = await fetch(url, options);const data = await response.json();console.log(data);} catch (error) {console.error('Error:', error);}}getJokes();
In this example, we define a function called getJokes
, marked as async
. Inside this function, we use the await
keyword to make the HTTP request using fetch, and then we parse the response using the json()
method. Finally, we log the data to the console.
Note that we wrap the entire request logic inside a try-catch block to catch any errors that might occur during the request. We also call the getJokes
function at the end to initiate the request.
Using node-fetch with TypeScript is a powerful way to make HTTP requests in your application. With the ability to add options to requests and use async/await, node-fetch offers a lot of flexibility for making HTTP requests.
If you now wants to learn how to test APIs, we have written a guide on Rapid API Client. It is a VS Code extension that allows you to test APIs directly from your code editor without the need to switch to a separate tool.