> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/angular/angular/llms.txt
> Use this file to discover all available pages before exploring further.

# HTTP Client Overview

> Introduction to Angular's HTTP client for making HTTP requests and handling responses

Angular's HTTP client provides a simplified API for HTTP functionality in your applications. It's built on top of the browser's native `fetch` or `XMLHttpRequest` APIs and provides a streamlined way to communicate with backend services.

## Key Features

* **Observable-based API**: All HTTP methods return RxJS Observables for powerful async operations
* **Request and response interceptors**: Transform requests and responses globally
* **Typed request and response objects**: Full TypeScript support with generic types
* **Streamlined error handling**: Structured error responses
* **Testability**: Built-in testing utilities for mocking HTTP requests
* **Progress events**: Track upload and download progress
* **Request cancellation**: Cancel in-flight requests when needed

## Getting Started

### Import HttpClient

To use the HTTP client, you need to import `HttpClient` and configure it in your application:

```typescript theme={null}
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';

@Component({
  selector: 'app-hero-list',
  template: `...`
})
export class HeroListComponent {
  private http = inject(HttpClient);
  
  getHeroes() {
    return this.http.get<Hero[]>('/api/heroes');
  }
}
```

### Provide HTTP Client

In your application configuration, provide the HTTP client:

```typescript theme={null}
import { provideHttpClient } from '@angular/common/http';
import { bootstrapApplication } from '@angular/platform-browser';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient()
  ]
});
```

## Making Requests

The `HttpClient` service provides methods for all common HTTP verbs:

* `get()` - Retrieve data from a server
* `post()` - Send data to create a resource
* `put()` - Send data to update a resource
* `patch()` - Send data to partially update a resource
* `delete()` - Delete a resource
* `head()` - Retrieve headers only
* `options()` - Retrieve supported HTTP methods
* `jsonp()` - Make JSONP requests

### Basic GET Request

```typescript theme={null}
interface Hero {
  id: number;
  name: string;
}

this.http.get<Hero[]>('/api/heroes')
  .subscribe(heroes => {
    console.log('Heroes:', heroes);
  });
```

### POST Request with Body

```typescript theme={null}
const newHero = { name: 'Spider-Man' };

this.http.post<Hero>('/api/heroes', newHero)
  .subscribe(hero => {
    console.log('Created hero:', hero);
  });
```

## Request Options

All HTTP methods accept an options object to customize the request:

```typescript theme={null}
this.http.get<Hero[]>('/api/heroes', {
  headers: { 'Authorization': 'Bearer token123' },
  params: { active: 'true' },
  responseType: 'json',
  observe: 'response',
  withCredentials: true
});
```

<ParamField path="headers" type="HttpHeaders | object">
  HTTP headers to send with the request
</ParamField>

<ParamField path="params" type="HttpParams | object">
  URL query parameters
</ParamField>

<ParamField path="responseType" type="'json' | 'text' | 'blob' | 'arraybuffer'">
  Expected response format (defaults to 'json')
</ParamField>

<ParamField path="observe" type="'body' | 'response' | 'events'">
  What to observe in the response (defaults to 'body')
</ParamField>

<ParamField path="withCredentials" type="boolean">
  Whether to send credentials (cookies) with the request
</ParamField>

<ParamField path="reportProgress" type="boolean">
  Whether to report upload/download progress events
</ParamField>

## Response Types

By default, `HttpClient` assumes JSON responses, but you can specify other types:

### JSON Response (default)

```typescript theme={null}
interface Config {
  apiUrl: string;
}

this.http.get<Config>('/api/config')
  .subscribe(config => {
    console.log('API URL:', config.apiUrl);
  });
```

### Text Response

```typescript theme={null}
this.http.get('/api/textfile', { responseType: 'text' })
  .subscribe(text => {
    console.log('File contents:', text);
  });
```

### Blob Response

```typescript theme={null}
this.http.get('/api/image.png', { responseType: 'blob' })
  .subscribe(blob => {
    const url = URL.createObjectURL(blob);
    // Use the blob URL
  });
```

## Observing Responses

Control what part of the response you want to observe:

### Body Only (default)

```typescript theme={null}
this.http.get<Hero[]>('/api/heroes')
  .subscribe(heroes => {
    // heroes is the response body
  });
```

### Full Response

```typescript theme={null}
this.http.get<Hero[]>('/api/heroes', { observe: 'response' })
  .subscribe(response => {
    console.log('Status:', response.status);
    console.log('Headers:', response.headers);
    console.log('Body:', response.body);
  });
```

### All Events

```typescript theme={null}
import { HttpEventType } from '@angular/common/http';

this.http.get('/api/data', { observe: 'events', reportProgress: true })
  .subscribe(event => {
    if (event.type === HttpEventType.DownloadProgress) {
      console.log(`Downloaded ${event.loaded} of ${event.total} bytes`);
    } else if (event.type === HttpEventType.Response) {
      console.log('Complete:', event.body);
    }
  });
```

## Error Handling

Handle HTTP errors using RxJS operators:

```typescript theme={null}
import { catchError, of } from 'rxjs';

this.http.get<Hero[]>('/api/heroes')
  .pipe(
    catchError(error => {
      console.error('Error loading heroes:', error);
      return of([]); // Return empty array as fallback
    })
  )
  .subscribe(heroes => {
    console.log('Heroes:', heroes);
  });
```

## HTTP Headers

Work with HTTP headers using the `HttpHeaders` class:

```typescript theme={null}
import { HttpHeaders } from '@angular/common/http';

const headers = new HttpHeaders()
  .set('Authorization', 'Bearer token123')
  .set('Content-Type', 'application/json');

this.http.get('/api/data', { headers })
  .subscribe(data => console.log(data));
```

Note: `HttpHeaders` is immutable, so `set()` returns a new instance.

## URL Parameters

Add query parameters using `HttpParams` or a plain object:

```typescript theme={null}
import { HttpParams } from '@angular/common/http';

// Using HttpParams
const params = new HttpParams()
  .set('page', '1')
  .set('limit', '10');

this.http.get('/api/heroes', { params })
  .subscribe(heroes => console.log(heroes));

// Using plain object
this.http.get('/api/heroes', { 
  params: { page: '1', limit: '10' } 
})
  .subscribe(heroes => console.log(heroes));
```

## Request Cancellation

Cancel in-flight requests by unsubscribing:

```typescript theme={null}
const subscription = this.http.get('/api/data')
  .subscribe(data => console.log(data));

// Cancel the request
subscription.unsubscribe();
```

## Related APIs

<CardGroup cols={2}>
  <Card title="HttpClient" icon="code" href="/api/http/http-client">
    Complete API reference for the HttpClient service
  </Card>

  <Card title="HttpInterceptor" icon="filter" href="/api/http/interceptor">
    Intercept and transform HTTP requests and responses
  </Card>
</CardGroup>

## See Also

* [HTTP Guide](https://angular.dev/guide/http)
* [HttpRequest](https://angular.dev/api/common/http/HttpRequest)
* [HttpResponse](https://angular.dev/api/common/http/HttpResponse)
* [HttpHeaders](https://angular.dev/api/common/http/HttpHeaders)
* [HttpParams](https://angular.dev/api/common/http/HttpParams)
