Get the response from an API using Nest.js

Malshani Wijekoon
2 min readMay 26, 2024

--

First you need to setup the nest.js in your local environment. refer this article for nest.js setup.

Once you setup the project create resource folders using following command.

nest g resource wines

Nest.js resources are set of files including controllers and services. See below image,

install ‘axios’ package. This will include in the package.json file.

sudo npm install axios
  1. In the service file (WinesService) add follwoing code
import { Injectable } from '@nestjs/common';
import axios from 'axios';

@Injectable()
export class WinesService {
async getRedWines(): Promise<any> {
try {
const response = await axios.get('https://api.sampleapis.com/wines/reds');
return response.data;
} catch (error) {
throw error;
}
}
}

2. Inject the WinesService into your controller to use the getRedWines method.

import { Controller, Get } from '@nestjs/common';
import { WinesService } from './wines.service';

@Controller('wines')
export class WinesController {
constructor(private readonly winesService: WinesService) {}

@Get('reds')
async getRedWines(): Promise<any> {
return this.winesService.getRedWines();
}
}

3. Finally, make sure your Nest.js application is properly configured to use the controller and service.

With this setup, when you make a GET request to /wines/reds endpoint of your Nest.js application, it will fetch the data from the provided API URL and return the JSON response.

--

--

Malshani Wijekoon
Malshani Wijekoon

No responses yet