DEV Community

Cover image for Include API Key In HTTP Requests
nightwolfdev
nightwolfdev

Posted on • Updated on • Originally published at nightwolf.dev

Include API Key In HTTP Requests

When making API requests, it’s common to include an API key. An API service will specify where to include the key for a successful response. In this article, learn how to use an Angular HttpInterceptor to include an API key as a Header or URL Param.

Implement HttpInterceptor Interface

The HttpInterceptor interface provides a means of intercepting HTTP requests and responses to transform or handle them before passing them along.

Let’s create a service that implements the HttpInterceptor interface.

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request);
  }
}
Enter fullscreen mode Exit fullscreen mode

Include API Key in Header

An example API service I used required the API key to be sent in a header called Authorization. The value must be the word key followed by the API key itself.

First, let’s check if the request is actually a request to the API host url.

const isApiRequest = request.url.startsWith('API_HOST_URL');
Enter fullscreen mode Exit fullscreen mode

If it is a request to the API host url, let’s clone the request and set the header with the required key.

if (isApiRequest) {
  request = request.clone({
    setHeaders: {
      'Authorization': 'key YOUR_API_KEY'
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Don’t forget to return the request!

return next.handle(request);
Enter fullscreen mode Exit fullscreen mode

Here’s the updated HttpInterceptor with the above code changes.

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const isApiRequest = request.url.startsWith('API_HOST_URL');

    if (isApiRequest) {
      request = request.clone({
        setHeaders: {
          'Authorization': 'key YOUR_API_KEY'
        }
      });
    }

    return next.handle(request);
  }
}
Enter fullscreen mode Exit fullscreen mode

Include API Key in URL Params

An example API service I used required the API key to be sent in a URL Param called api_key. The value must be the API key itself.

First, let’s check if the request is actually a request to the API host url.

const isApiRequest = request.url.startsWith('API_HOST_URL');
Enter fullscreen mode Exit fullscreen mode

If it is a request to the API host url, let’s clone the request and set the url param with the required key.

if (isApiRequest) {
  request = request.clone({
    setParams: {
      'api_key': 'YOUR_API_KEY'
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Don’t forget to return the request!

return next.handle(request);
Enter fullscreen mode Exit fullscreen mode

Here’s the updated HttpInterceptor with the above code changes.

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const isApiRequest = request.url.startsWith('API_HOST_URL');

    if (isApiRequest) {
      request = request.clone({
        setParams: {
          'api_key': 'YOUR_API_KEY'
        }
      });
    }

    return next.handle(request);
  }
}
Enter fullscreen mode Exit fullscreen mode

Provide the Interceptor

In order to actually use the interceptor, you have to define it as a provider in whatever module you want to use it in. In my particular use case, I provided it in the app module so I could intercept network requests across the entire application.

import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { RequestInterceptor } from '/path/to/interceptor';

@NgModule({
  ..
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }
  ]
  ..
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

You can use multiple interceptors, but keep in mind that Angular provides them in the order that you provide them. For example, if you provide interceptors A, then B, then C, requests will flow in A > B > C and responses will flow out C > B > A.


Visit our website at https://nightwolf.dev and follow us on Twitter!

Top comments (2)

 
nightwolfdev profile image
nightwolfdev

Would startsWith be better than includes?

Collapse
 
nightwolfdev profile image
nightwolfdev

Do you have a recommendation for avoiding that potential if you still want to apply it to only the host in question?