HTTP Service
import path: @azure-net/kit/infra
Main HTTP client for making API requests.
Creating HTTP Service
typescript
import { HttpService } from '@azure-net/kit/infra';
const httpService = new HttpService({
baseUrl: 'https://api.example.com',
baseOptions: {
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
},
onRequest: (options) => {
// Modify options before request (called before each request)
const token = getAuthToken();
if (token) {
options.headers = {
...options.headers,
'Authorization': `Bearer ${token}`
};
}
},
onError: (error) => {
// Error handling in the error key instance HttpServiceError
// After processing, be sure to return the error; it must remain an HttpServiceError instance at this stage
console.error('HTTP Error:', error);
return error;
}
});Making requests
typescript
// GET request
const users = await httpService.get<User[]>('/users');
// POST request with data
const newUser = await httpService.post<User>('/users', {
json: {
name: 'John Doe',
email: 'john@example.com'
}
}); // Requests with data sending also support body for sending data; json sends JSON directly by converting the object
// Different response formats
const blob = await httpService.get<Blob>('/files/document.pdf', {
responseFormat: 'blob'
});
const text = await httpService.get<string>('/health', {
responseFormat: 'text'
});
// PUT, PATCH, DELETE
await httpService.put<User>(`/users/${id}`, { json: updateData });
await httpService.patch<User>(`/users/${id}`, { json: partialData });
await httpService.delete(`/users/${id}`);Response and error types
typescript
export interface IHttpServiceResponse<YourResponseData> {
headers: Record<string, string>;
status: number;
success: boolean;
data: YourResponseData;
message: string;
}
export interface IHttpServiceError<YourErrorResponse> extends IHttpServiceResponse<YourErrorResponse> {
original?: Error;
}Allowed response formats (responseFormat key)
- json - will return the data key in HttpServiceResponse as JSON
- blob - will return the data key in HttpServiceResponse as blob
- text - will return the data key in HttpServiceResponse as text
- arrayBuffer - will return the data key in HttpServiceResponse as arrayBuffer
- body - will return the basic response body
(ReadableStream<Uint8Array>)
Allowed baseOptions and options when requesting
Under the hood, HttpService uses ky, meaning you can use all basic fetch options plus those available in ky, such as json, in options.