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

# HttpClient

> API reference for Angular's HttpClient service for making HTTP requests

The `HttpClient` service is Angular's primary interface for making HTTP requests. It provides methods for all common HTTP operations and returns RxJS Observables for handling asynchronous responses.

## Class Definition

```typescript theme={null}
class HttpClient {
  request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>;
  request(method: string, url: string, options?: {...}): Observable<any>;
  
  delete(url: string, options?: {...}): Observable<any>;
  get(url: string, options?: {...}): Observable<any>;
  head(url: string, options?: {...}): Observable<any>;
  jsonp<T>(url: string, callbackParam: string): Observable<T>;
  options(url: string, options?: {...}): Observable<any>;
  patch(url: string, body: any, options?: {...}): Observable<any>;
  post(url: string, body: any, options?: {...}): Observable<any>;
  put(url: string, body: any, options?: {...}): Observable<any>;
}
```

## Importing

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

class MyService {
  private http = inject(HttpClient);
}
```

## Methods

### request()

Constructs an observable for a generic HTTP request.

<CodeGroup>
  ```typescript Basic Request theme={null}
  const req = new HttpRequest('GET', '/api/heroes');
  this.http.request(req).subscribe(event => {
    console.log(event);
  });
  ```

  ```typescript String Method theme={null}
  this.http.request('GET', '/api/heroes', {
    responseType: 'json'
  }).subscribe(data => {
    console.log(data);
  });
  ```

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

  this.http.request<Hero[]>('GET', '/api/heroes')
    .subscribe(heroes => {
      console.log(heroes);
    });
  ```
</CodeGroup>

<ParamField path="method" type="string" required>
  HTTP method (GET, POST, PUT, DELETE, etc.)
</ParamField>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="options" type="object">
  Configuration options for the request

  <Expandable title="Options">
    <ParamField path="body" type="any">
      Request body
    </ParamField>

    <ParamField path="headers" type="HttpHeaders | object">
      HTTP headers
    </ParamField>

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

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

    <ParamField path="responseType" type="'json' | 'text' | 'blob' | 'arraybuffer'" default="'json'">
      Expected response format
    </ParamField>

    <ParamField path="reportProgress" type="boolean" default="false">
      Whether to report progress events
    </ParamField>

    <ParamField path="withCredentials" type="boolean" default="false">
      Whether to send credentials (cookies)
    </ParamField>

    <ParamField path="context" type="HttpContext">
      Request context for passing data to interceptors
    </ParamField>

    <ParamField path="timeout" type="number">
      Request timeout in milliseconds
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="return" type="Observable<any>">
  An Observable of the HTTP response
</ResponseField>

### get()

Constructs a GET request that interprets the body as JSON by default.

<CodeGroup>
  ```typescript Basic GET theme={null}
  this.http.get('/api/heroes')
    .subscribe(data => console.log(data));
  ```

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

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

  ```typescript With Options theme={null}
  this.http.get<Hero[]>('/api/heroes', {
    params: { active: 'true' },
    headers: { 'Authorization': 'Bearer token' }
  }).subscribe(heroes => {
    console.log(heroes);
  });
  ```

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

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

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response body (type T)
</ResponseField>

### post()

Constructs a POST request that sends data to the server.

<CodeGroup>
  ```typescript Basic POST theme={null}
  const newHero = { name: 'Spider-Man' };

  this.http.post('/api/heroes', newHero)
    .subscribe(result => console.log(result));
  ```

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

  const newHero = { name: 'Spider-Man' };

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

  ```typescript With Headers theme={null}
  const headers = { 'Content-Type': 'application/json' };

  this.http.post('/api/heroes', newHero, { headers })
    .subscribe(result => console.log(result));
  ```

  ```typescript Form Data theme={null}
  const formData = new FormData();
  formData.append('name', 'Spider-Man');
  formData.append('avatar', fileBlob);

  this.http.post('/api/heroes', formData)
    .subscribe(result => console.log(result));
  ```
</CodeGroup>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="body" type="any" required>
  The content to post
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response body (type T)
</ResponseField>

### put()

Constructs a PUT request that replaces a resource on the server.

<CodeGroup>
  ```typescript Basic PUT theme={null}
  const updatedHero = { id: 1, name: 'Iron Man' };

  this.http.put('/api/heroes/1', updatedHero)
    .subscribe(result => console.log(result));
  ```

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

  const updatedHero = { id: 1, name: 'Iron Man' };

  this.http.put<Hero>('/api/heroes/1', updatedHero)
    .subscribe(hero => {
      console.log('Updated:', hero.name);
    });
  ```
</CodeGroup>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="body" type="any" required>
  The content to update
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response body (type T)
</ResponseField>

### patch()

Constructs a PATCH request that partially updates a resource on the server.

<CodeGroup>
  ```typescript Basic PATCH theme={null}
  const partialUpdate = { name: 'Captain America' };

  this.http.patch('/api/heroes/1', partialUpdate)
    .subscribe(result => console.log(result));
  ```

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

  this.http.patch<Hero>('/api/heroes/1', { name: 'Thor' })
    .subscribe(hero => {
      console.log('Updated hero:', hero);
    });
  ```
</CodeGroup>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="body" type="any" required>
  The content to patch
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response body (type T)
</ResponseField>

### delete()

Constructs a DELETE request that removes a resource from the server.

<CodeGroup>
  ```typescript Basic DELETE theme={null}
  this.http.delete('/api/heroes/1')
    .subscribe(() => console.log('Deleted'));
  ```

  ```typescript DELETE with Body theme={null}
  this.http.delete('/api/heroes/1', {
    body: { reason: 'duplicate' }
  }).subscribe(() => console.log('Deleted'));
  ```

  ```typescript Observe Response theme={null}
  this.http.delete('/api/heroes/1', { 
    observe: 'response' 
  }).subscribe(response => {
    console.log('Status:', response.status);
  });
  ```
</CodeGroup>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response body (type T)
</ResponseField>

### head()

Constructs a HEAD request that retrieves only headers without the body.

<CodeGroup>
  ```typescript Basic HEAD theme={null}
  this.http.head('/api/heroes', { observe: 'response' })
    .subscribe(response => {
      console.log('Content-Type:', response.headers.get('Content-Type'));
      console.log('Content-Length:', response.headers.get('Content-Length'));
    });
  ```

  ```typescript Check Resource Existence theme={null}
  this.http.head('/api/heroes/1', { observe: 'response' })
    .subscribe(
      response => console.log('Hero exists:', response.status === 200),
      error => console.log('Hero not found:', error.status === 404)
    );
  ```
</CodeGroup>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response (typically used with observe: 'response')
</ResponseField>

### options()

Constructs an OPTIONS request that retrieves supported HTTP methods.

```typescript theme={null}
this.http.options('/api/heroes', { observe: 'response' })
  .subscribe(response => {
    const allowedMethods = response.headers.get('Allow');
    console.log('Allowed methods:', allowedMethods);
  });
```

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="options" type="object">
  Configuration options (see request() method)
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response
</ResponseField>

### jsonp()

Constructs a JSONP request for cross-domain requests.

```typescript theme={null}
this.http.jsonp('https://api.example.com/data', 'callback')
  .subscribe(data => {
    console.log('JSONP data:', data);
  });
```

<Note>
  JSONP requires the `provideHttpClient()` to be configured with `withJsonpSupport()`.
</Note>

<ParamField path="url" type="string" required>
  The endpoint URL
</ParamField>

<ParamField path="callbackParam" type="string" required>
  The callback query parameter name
</ParamField>

<ResponseField name="return" type="Observable<T>">
  An Observable of the response body (type T)
</ResponseField>

## Usage Notes

### Type Safety

Use TypeScript generics to ensure type safety:

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

// TypeScript knows that 'user' is of type User
this.http.get<User>('/api/user/1')
  .subscribe(user => {
    console.log(user.email); // Type-safe access
  });
```

### Response Type Variations

The return type varies based on the `observe` and `responseType` options:

```typescript theme={null}
// Returns Observable<T> (body only)
this.http.get<T>('/api/data');

// Returns Observable<HttpResponse<T>> (full response)
this.http.get<T>('/api/data', { observe: 'response' });

// Returns Observable<HttpEvent<T>> (all events)
this.http.get<T>('/api/data', { observe: 'events' });

// Returns Observable<string> (text response)
this.http.get('/api/data', { responseType: 'text' });

// Returns Observable<Blob> (blob response)
this.http.get('/api/data', { responseType: 'blob' });

// Returns Observable<ArrayBuffer> (arraybuffer response)
this.http.get('/api/data', { responseType: 'arraybuffer' });
```

### Progress Tracking

Track upload and download progress:

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

this.http.post('/api/upload', fileData, {
  reportProgress: true,
  observe: 'events'
}).subscribe(event => {
  if (event.type === HttpEventType.UploadProgress) {
    const progress = Math.round(100 * event.loaded / event.total!);
    console.log(`Upload progress: ${progress}%`);
  } else if (event.type === HttpEventType.Response) {
    console.log('Upload complete:', event.body);
  }
});
```

### Error Handling

Handle errors using RxJS operators:

```typescript theme={null}
import { catchError, retry } from 'rxjs/operators';
import { throwError } from 'rxjs';

this.http.get<Hero[]>('/api/heroes')
  .pipe(
    retry(3), // Retry up to 3 times
    catchError(error => {
      console.error('Error:', error);
      return throwError(() => new Error('Failed to load heroes'));
    })
  )
  .subscribe(heroes => {
    console.log(heroes);
  });
```

## See Also

<CardGroup cols={2}>
  <Card title="HTTP Overview" icon="book" href="/api/http/overview">
    Introduction to Angular's HTTP client
  </Card>

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

## Related Types

* [HttpRequest](https://angular.dev/api/common/http/HttpRequest) - Represents an HTTP request
* [HttpResponse](https://angular.dev/api/common/http/HttpResponse) - Represents an HTTP response
* [HttpHeaders](https://angular.dev/api/common/http/HttpHeaders) - Represents HTTP headers
* [HttpParams](https://angular.dev/api/common/http/HttpParams) - Represents HTTP URL parameters
* [HttpEvent](https://angular.dev/api/common/http/HttpEvent) - Union type for HTTP events
* [HttpErrorResponse](https://angular.dev/api/common/http/HttpErrorResponse) - Represents an HTTP error response
