Include API Key In HTTP Requests
Tags: angular, api, webdev, tutorial
Published: 2022-12-01 21:32:54

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](https://angular.io/api/common/http/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.

```javascript
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);
  }
}
```

## 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.

```javascript
const isApiRequest = request.url.startsWith('API_HOST_URL');
```

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

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

Don’t forget to return the request!

```javascript
return next.handle(request);
```

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

```javascript
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);
  }
}
```

## 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.

```javascript
const isApiRequest = request.url.startsWith('API_HOST_URL');
```

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

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

Don’t forget to return the request!

```javascript
return next.handle(request);
```

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

```javascript
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);
  }
}
```

## 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.

```javascript
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 {}
```

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](https://nightwolf.dev) and follow us on [Twitter](https://twitter.com/nightwolfdev)!**