NestJS, a progressive Node.js framework for building efficient, reliable, and scalable server-side applications, continues to gain popularity among developers. One crucial aspect of backend development is integrating third-party APIs to either enrich your application’s functionality or seamlessly interact with other services. In this article, let’s walk through how to integrate third-party APIs with NestJS using TypeScript.
Why NestJS?
NestJS is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming). Its modular architecture is especially appealing for building enterprise-level applications. Let’s dive into integrating third-party APIs in this robust framework.
Setting Up the Project
First, create a new NestJS project if you don’t have one already:
$ npm i -g @nestjs/cli
$ nest new third-party-integration
$ cd third-party-integration
Installing Dependencies
For this example, we’ll be using Axios to facilitate HTTP requests. Install Axios and its TypeScript types:
$ npm install axios
$ npm install @types/axios
Creating a Service for API Integration
NestJS encourages a modular architecture. For third-party API integration, creating a dedicated service is a good practice. Generate a new service:
$ nest generate service third-party
Open the newly created third-party.service.ts
file and modify it as follows:
import { Injectable, HttpService } from '@nestjs/common';
import { AxiosResponse } from 'axios';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class ThirdPartyService {
constructor(private httpService: HttpService) {}
// Example: Fetching data from a hypothetical Weather API
fetchWeatherData(city: string): Observable<AxiosResponse<any>> {
const API_KEY = 'your_api_key_here';
const url = `https://api.exampleweather.com/data/2.5/weather?q=${city}&appid=${API_KEY}`;
return this.httpService.get(url).pipe(
map((response) => response.data)
);
}
}
Using the Service in a Controller
Now, create a controller to expose an endpoint that uses the ThirdPartyService
. Generate a new controller:
$ nest generate controller weather
Modify the weather.controller.ts
file to use the ThirdPartyService
:
import { Controller, Get, Query } from '@nestjs/common';
import { ThirdPartyService } from './third-party/third-party.service';
import { Observable } from 'rxjs';
import { AxiosResponse } from 'axios';
@Controller('weather')
export class WeatherController {
constructor(private readonly thirdPartyService: ThirdPartyService) {}
@Get()
getWeather(@Query('city') city: string): Observable<AxiosResponse<any>> {
return this.thirdPartyService.fetchWeatherData(city);
}
}
Registering HttpModule
To use HttpService
, import and register HttpModule
in your application's root module (AppModule
):
import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { WeatherController } from './weather/weather.controller';
import { ThirdPartyService } from './third-party/third-party.service';
@Module({
imports: [HttpModule],
controllers: [WeatherController],
providers: [ThirdPartyService],
})
export class AppModule {}
Testing the Integration
With everything set up, run your application:
$ npm run start
Now you can test your endpoint by navigating to http://localhost:3000/weather?city=London
.
Error Handling
Error handling is crucial for real-world applications. Modify your ThirdPartyService
to handle errors gracefully:
import { Injectable, HttpService, HttpException } from '@nestjs/common';
import { AxiosResponse } from 'axios';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Injectable()
export class ThirdPartyService {
constructor(private httpService: HttpService) {}
fetchWeatherData(city: string): Observable<AxiosResponse<any>> {
const API_KEY = 'your_api_key_here';
const url = `https://api.exampleweather.com/data/2.5/weather?q=${city}&appid=${API_KEY}`;
return this.httpService.get(url).pipe(
map((response) => response.data),
catchError((error) => {
return throwError(new HttpException(error.response.data, error.response.status));
})
);
}
}
Conclusion
Integrating third-party APIs with NestJS is straightforward and efficient, thanks to its modular and easily extensible architecture. By following this guide, you can set up a robust service layer to interact with external APIs seamlessly. Experiment with other APIs and explore the various features NestJS offers to enhance your applications further.
Happy coding!