Response types

The Aurelia Fetch Client provides comprehensive support for all standard response types and data formats. Understanding how to properly handle different response types is crucial for building robust applications that work with various APIs and data sources.

Response Type Detection

The fetch client automatically handles content-type detection, but you should always check response headers and status codes for proper error handling:

import { IHttpClient } from '@aurelia/fetch-client';
import { resolve } from '@aurelia/kernel';

export class ApiService {
  private http = resolve(IHttpClient);

  async fetchWithTypeDetection(url: string) {
    const response = await this.http.get(url);
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const contentType = response.headers.get('content-type') || '';
    
    if (contentType.includes('application/json')) {
      return await response.json();
    } else if (contentType.includes('text/')) {
      return await response.text();
    } else if (contentType.includes('image/') || contentType.includes('application/octet-stream')) {
      return await response.blob();
    } else {
      return await response.arrayBuffer();
    }
  }
}

JSON Responses

JSON is the most common response type for modern APIs. Always include proper error handling and type safety:

Binary Data (Images, Files, Documents)

Handle binary data like images, PDFs, and other files using Blob responses:

Text Responses

Handle plain text, HTML, CSV, and other text-based responses:

ArrayBuffer for Raw Binary Data

Use ArrayBuffer for handling raw binary data that needs processing:

Streaming Responses

Handle large responses using streams for better memory efficiency:

Response Transformation with Interceptors

Use interceptors to transform responses globally or conditionally:

Error Response Handling

Properly handle different types of error responses:

Best Practices

Content-Type Validation

Always check content-type headers before processing responses:

Memory Management

For large responses, use streaming or dispose of object URLs:

Type Safety

Use TypeScript interfaces for JSON responses:

Error Boundaries

Always wrap response processing in try-catch blocks and handle different error types appropriately.

Last updated

Was this helpful?