Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 42 ยท Building Real APIs

Calling External APIs with HttpModule

Call external APIs from NestJS with @nestjs/axios: HttpModule and HttpService, firstValueFrom, timeouts, retries with backoff, and mapping upstream errors to clean responses.

Few back ends live alone. Your API checks a payment with one service, fetches exchange rates from another and sends mail through a third. Calling those services looks easy (fetch(url)), but the details decide whether your API stays healthy when a partner is slow or broken: timeouts, retries, error mapping and testability. Nest gives you HttpModule and HttpService, a thin wrapper around the Axios HTTP client, so that these calls become injectable providers like everything else.

This lesson shows how to register HttpModule, call an API with HttpService, turn its RxJS result into a promise with firstValueFrom, and then build the habits that matter in production. The Nest code is read-only because it needs npm. The stand-ins are real: they start a loopback server that plays a flaky partner API and call it with Node's built-in fetch, with the same timeout, retry and error-mapping logic you would put around HttpService.

Setting up HttpModule

Install @nestjs/axios and axios. Import HttpModule in the feature module that needs it. register sets defaults for every call made by that module:

TypeScript
import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';

@Module({
  imports: [
    HttpModule.register({
      baseURL: 'https://rates.example.com/v1',
      timeout: 3000,
      maxRedirects: 3,
    }),
  ],
  providers: [RatesService],
  exports: [RatesService],
})
export class RatesModule {}

As with other modules, there is an async form, HttpModule.registerAsync({ inject: [ConfigService], useFactory: ... }), for values that come from configuration, such as a base URL or an API key. Because each module that imports HttpModule gets its own settings, you can give the payment module a 10-second timeout and the rates module a 3-second one.

HttpService and RxJS

HttpService mirrors Axios: get, post, put, patch, delete, each taking a URL and an optional config. The important twist is the return type. Nest's HttpService returns an RxJS Observable, not a promise, which is why the same operators you used in Interceptors work here. Most of the time you want a promise, and firstValueFrom converts one:

TypeScript
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';

@Injectable()
export class RatesService {
  constructor(private readonly http: HttpService) {}

  async latest(base: string) {
    const response = await firstValueFrom(
      this.http.get<RatesResponse>('/latest', { params: { base } }),
    );
    return response.data;
  }
}

firstValueFrom subscribes, waits for the first emitted value (an HTTP call emits exactly one, the Axios response) and resolves with it. If the observable errors, the promise rejects. The response is the full Axios response: data holds the parsed JSON body, and status and headers are there too. Axios rejects by default for status codes outside 2xx, with an AxiosError that carries error.response (when the server answered) or no response at all (network failure or timeout).

Do not call lastValueFrom or firstValueFrom on a stream that never completes or emits. An HTTP observable is fine, but if you convert a different, long-lived stream you will wait forever.

Timeouts are not optional

Without a timeout, a partner that accepts the connection and then stalls will hold your request open, along with memory and a connection from your pool. Under load, one slow dependency can exhaust your server. Always set a timeout on the client (timeout: 3000 above), and pick a value smaller than the limit your own callers or your load balancer have, so you fail with a clear error instead of being cut off.

Be precise about what a timeout covers. A "total request" timeout is the number you usually want. Separate connect or read-idle timeouts exist in some clients. Whatever your tool offers, test it: start a server that never answers and make sure your call ends.

Retries with backoff

Networks fail in small ways: a dropped connection, a 503 while a partner restarts. A retry often succeeds, but careless retries cause outages of their own. Follow these rules:

  • Retry only idempotent calls (GET, PUT, DELETE) and calls made safe with an idempotency key. Retrying a POST /charges without one can charge a customer twice.
  • Retry only transient failures: timeouts, connection errors, 502, 503, 504 and 429 (honoring Retry-After). Never retry 400, 401, 403 or 404; the answer will not change.
  • Use exponential backoff with jitter: wait 200 ms, 400 ms, 800 ms, each with some random variation, so thousands of clients do not retry in lockstep.
  • Cap the number of attempts (two or three) and the total time.

With RxJS you can write this inside the pipeline:

TypeScript
import { firstValueFrom, retry, timer, catchError, throwError } from 'rxjs';

const response = await firstValueFrom(
  this.http.get('/latest').pipe(
    retry({
      count: 2,
      delay: (error, attempt) =>
        isTransient(error) ? timer(2 ** attempt * 200) : throwError(() => error),
    }),
    catchError((error) => throwError(() => this.toHttpException(error))),
  ),
);

The delay function decides per error whether to wait and retry or to rethrow immediately. (Check the RxJS documentation for your version; the retry({ count, delay }) form is the modern one.) Retries multiply load on a struggling partner, so many teams add a circuit breaker that stops calling a dependency for a while after repeated failures. That is beyond this lesson, but now you know why it exists.

Mapping upstream errors

When your API calls a partner and the partner fails, what should your client see? Passing the partner's raw error through leaks internals and confuses clients. Translate it into an error that describes your service's situation, using the exceptions from Exception Filters and Errors:

What happened upstream What your API returns
Timeout or no connection 504 Gateway Timeout (GatewayTimeoutException)
Partner answered 5xx 502 Bad Gateway (BadGatewayException)
Partner answered 404 for a resource the user asked for 404 Not Found
Partner answered 401 or 403 to your credentials 502 or 500, and log it: it is your configuration, not the user's fault
Partner answered 429 503 Service Unavailable with Retry-After
TypeScript
private toHttpException(error: AxiosError) {
  if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
    return new GatewayTimeoutException('The rates service did not respond in time');
  }
  const status = error.response?.status;
  if (status === 404) return new NotFoundException('Unknown currency');
  return new BadGatewayException('The rates service failed');
}

Log the upstream status and a request id yourself; just do not return secrets or stack traces to the client.

Testing code that calls other APIs

Never let unit tests hit the real network. Because HttpService is an ordinary provider, you replace it in a test with { provide: HttpService, useValue: { get: jest.fn(() => of({ data: ... })) } } (using RxJS's of), as shown in Testing Nest Applications. For end-to-end tests of failure behavior, a small fake HTTP server (like the one below) is even better, because it exercises real timeouts and real status codes.

Stand-in: timeout and error mapping

This first stand-in starts a loopback server with three behaviors: a fast good answer, a 503, and a handler that never answers. A RatesClient calls it with fetch and an AbortSignal.timeout, then maps failures the way toHttpException does above. HttpService and Axios are replaced by fetch.

Node.js A timeout and an error mapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The hanging endpoint ends after about 300 ms with a 504, not after minutes. The partner's 503 becomes a 502 from your service: you are the gateway, and the failure is upstream. This is the mapping to make inside a Nest filter or service.

Stand-in: retry with backoff on transient errors

Now a partner that fails twice and then succeeds, plus a client that retries only transient failures with exponential backoff. The wait times are small so the demo is fast. It also proves that a 404 is not retried.

Node.js Retrying only what can succeed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The flaky endpoint succeeds on the third attempt. The 404 stops at once, because retrying a "not found" cannot change the answer and only adds load. In a real service, add a cap on total time and never retry unsafe calls without an idempotency key.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Nest's HttpService.get() returns what, and how do you usually turn it into a promise?

    HttpService wraps Axios and returns observables. firstValueFrom waits for the single emitted response and resolves with it.
  2. 2. Why should every external call have a timeout?

    Without a timeout, one slow dependency can tie up all your resources. Failing fast keeps your own service responsive.
  3. 3. Which failure is safe to retry (for an idempotent GET)?

    503 is transient and may succeed later. 400, 401 and 404 will give the same answer if repeated.
  4. 4. A partner replies 500 to your server's call. What should your API return to its own client?

    Translate upstream failures into your own error semantics, and keep internal detail in logs.
  5. 5. Why use backoff with jitter?

    Growing, randomized delays spread retries over time and give the partner room to recover.

Summary

  • @nestjs/axios provides HttpModule (register / registerAsync) and an injectable HttpService that wraps Axios.
  • HttpService methods return Observables; use firstValueFrom to get a promise of the Axios response, and read response.data.
  • Always set timeouts, retry only idempotent calls and transient errors with exponential backoff and jitter, and cap the attempts.
  • Map upstream failures to your own errors (504 for timeouts, 502 for upstream 5xx) and log the details.
  • Replace HttpService with a fake in unit tests, and use a small fake server to test timeouts and status codes for real.

Next, expose your data through a GraphQL schema in GraphQL with NestJS.