How to call an API in NestJS?

Member

by viviane , in category: JavaScript , a year ago

How to call an API in NestJS?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by porter.bins , a year ago

@viviane 

To call an API in NestJS, you can use the HttpService provided by the @nestjs/common package. Here's an example of how you can use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { HttpService, Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(private readonly httpService: HttpService) {}

  async getData(): Promise<any> {
    const response = await this.httpService.get('http://example.com/api/endpoint').toPromise();
    return response.data;
  }
}


In this example, the AppService is making a GET request to the specified API endpoint using the httpService.get() method. The toPromise() method is used to convert the Observable returned by the get() method into a promise, which allows us to use the await keyword to wait for the response.


You can also use other methods such as post(), put(), and delete() to make different types of HTTP requests.


It's also a good idea to handle error cases, for example by wrapping the API call in a try-catch block and throwing an appropriate error.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { HttpService, Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(private readonly httpService: HttpService) {}

  async getData(): Promise<any> {
    try {
      const response = await this.httpService.get('http://example.com/api/endpoint').toPromise();
      return response.data;
    } catch (error) {
      throw new HttpException('Failed to fetch data', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}


I hope this helps! Let me know if you have any questions.

Member

by carlo , 4 months ago

@viviane 

The given code is correct and can be used to call an API in NestJS. Additionally, you can also configure the HttpService to send headers, set query parameters, and handle other API request-related tasks. Here's an example of how you can perform these tasks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { HttpService, Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(private readonly httpService: HttpService) {}

  async getData(): Promise<any> {
    try {
      const headers = { Authorization: 'Bearer ***xx' }; // Example header
      const params = { page: 1, limit: 10 }; // Example query parameters
      
      // Make the API call with headers and query parameters
      const response = await this.httpService.get('http://example.com/api/endpoint', { headers, params }).toPromise();
      return response.data;
    } catch (error) {
      throw new HttpException('Failed to fetch data', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}


In this example, the headers and params variables are used to set the headers and query parameters of the API request respectively. These variables are then passed as options to the get() method of the httpService. You can modify the headers and params objects to fit your specific use case.


I hope this clarifies how to call an API in NestJS. Let me know if you have any further questions!