docs/pages/advanced/api-reference.md
Below is a list of all the available functions and classes in the axios package. These functions may be used and imported in your project. All of these functions and classes are protected by our renewed promise to follow semantic versioning. This means that you can rely on these functions and classes to remain stable and unchanged in future releases unless a major version change is made.
The axios instance is the main object that you will use to make HTTP requests. It is a factory function that creates a new instance of the Axios class. The axios instance has a number of methods that you can use to make HTTP requests. These methods are documented in the Request aliases section of the documentation.
AxiosThe Axios class is the main class that you will use to make HTTP requests. It is a factory function that creates a new instance of the Axios class. The Axios class has a number of methods that you can use to make HTTP requests. These methods are documented in the Request aliases section of the documentation.
constructorCreates a new instance of the Axios class. The constructor takes an optional configuration object as an argument.
constructor(instanceConfig?: AxiosRequestConfig);
requestHandles request invocation and response resolution. This is the main method that you will use to make HTTP requests. It takes a configuration object as an argument and returns a promise that resolves to the response object.
request(configOrUrl: string | AxiosRequestConfig<D>, config: AxiosRequestConfig<D>): Promise<AxiosResponse<T>>;
CancelToken <Badge type="danger" text="Deprecated in favour of AbortController" />The CancelToken class was based on the tc39/proposal-cancelable-promises proposal. It was used to create a token that could be used to cancel an HTTP request. The CancelToken class is now deprecated in favour of the AbortController API.
As of version 0.22.0, the CancelToken class is deprecated and will be removed in a future release. It is recommended that you use the AbortController API instead.
The class is exported mainly for backwards compatibility and will be removed in a future release. We strongly discourage its use in new projects; the legacy interop helpers below are listed only for existing code.
The legacy methods remain typed for existing integrations:
subscribe(listener: (cancel: Cancel | any) => void): void;
unsubscribe(listener: (cancel: Cancel | any) => void): void;
toAbortSignal(): AbortSignal;
AxiosErrorThe AxiosError class is an error class that is thrown when an HTTP request fails. It extends the Error class and adds additional properties to the error object.
constructorCreates a new instance of the AxiosError class. The constructor takes an optional message, code, config, request, and response as arguments.
constructor(message?: string, code?: string, config?: InternalAxiosRequestConfig<D>, request?: any, response?: AxiosResponse<T, D>);
propertiesThe AxiosError class provides the following properties:
// Config instance.
config?: InternalAxiosRequestConfig<D>;
// Error code.
code?: string;
// Request instance.
request?: any;
// Response instance.
response?: AxiosResponse<T, D>;
// Boolean indicating if the error is an `AxiosError`.
isAxiosError: boolean;
// Error status code.
status?: number;
// Helper method to convert the error to a JSON object.
toJSON: () => object;
// Error cause.
cause?: Error;
AxiosHeadersThe AxiosHeaders class is a utility class that is used to manage HTTP headers. It provides methods for manipulating headers, such as adding, removing, and getting headers.
Only the main methods are documented here. For a full list of methods, please refer to the type declaration file.
constructorCreates a new instance of the AxiosHeaders class. The constructor takes an optional headers object as an argument.
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
setAdds a header to the headers object. Empty or whitespace-only header names are ignored.
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
set(headers?: Iterable<[string, AxiosHeaderValue]>, rewrite?: boolean): AxiosHeaders;
getGets a header from the headers object.
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
hasChecks if a header exists in the headers object.
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
deleteRemoves a header from the headers object.
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clearRemoves all headers from the headers object.
clear(matcher?: AxiosHeaderMatcher): boolean;
normalizeNormalizes the headers object.
normalize(format: boolean): AxiosHeaders;
concatConcatenates headers objects.
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
toJSONConverts the headers object to a JSON object.
toJSON(asStrings: true): Record<string, string>;
toJSON(asStrings?: false): Record<string, string | string[]>;
toStringReturns the headers as a CRLF-free HTTP header block, one name: value pair per line.
toString(): string;
CanceledError <Badge type="tip" text="Extended AxiosError" />The CanceledError class is an error class that is thrown when an HTTP request is canceled. It extends the AxiosError class.
constructor(message?: string, config?: InternalAxiosRequestConfig, request?: any);
__CANCEL__?: boolean;
Cancel <Badge type="tip" text="Alias for CanceledError" />The Cancel class is an alias for the CanceledError class. It is exported for backwards compatibility and will be removed in a future release.
Cancel: typeof CanceledError;
isCancelA function that checks if an error is a CanceledError. Useful for distinguishing intentional cancellations from unexpected errors.
isCancel<T = any>(value: any): value is CanceledError<T>;
import axios from 'axios';
const controller = new AbortController();
axios.get('/api/data', { signal: controller.signal }).catch((error) => {
if (axios.isCancel(error)) {
console.log('Request was cancelled:', error.message);
} else {
console.error('Unexpected error:', error);
}
});
controller.abort('User navigated away');
isAxiosErrorA function that checks if an error is an AxiosError. Use this in catch blocks to safely access axios-specific error properties like error.response and error.config.
isAxiosError(value: any): value is AxiosError;
import axios from 'axios';
try {
await axios.get('/api/resource');
} catch (error) {
if (axios.isAxiosError(error)) {
// error.response, error.config, error.code are all available
console.error('HTTP error', error.response?.status, error.message);
} else {
// A non-axios error (e.g. a programming mistake)
throw error;
}
}
all <Badge type="danger" text="Deprecated in favour of Promise.all" />The all function is a utility function that takes an array of promises and returns a single promise that resolves when all of the promises in the array have resolved. The all function is now deprecated in favour of the Promise.all method. It is recommended that you use the Promise.all method instead.
As of version 0.22.0, the all function is deprecated and will be removed in a future release. It is recommended that you use the Promise.all method instead.
spreadThe spread function is a utility function that can be used to spread an array of arguments into a function call. This is useful when you have an array of arguments that you want to pass to a function that takes multiple arguments.
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
toFormDataConverts a plain JavaScript object (or a nested one) to a FormData instance. Useful when you want to programmatically build multipart form data from an object.
toFormData(sourceObj: object, formData?: FormData, options?: FormSerializerOptions): FormData;
import { toFormData } from 'axios';
const data = { name: 'Jay', avatar: fileBlob };
const form = toFormData(data);
// form is now a FormData instance ready to post
await axios.post('/api/users', form);
formToJSONConverts a FormData instance back to a plain JavaScript object. Useful for reading form data in a structured format.
formToJSON(form: FormData): object;
import { formToJSON } from 'axios';
const form = new FormData();
form.append('name', 'Jay');
form.append('role', 'admin');
const obj = formToJSON(form);
console.log(obj); // { name: "Jay", role: "admin" }
getAdapterResolves and returns an adapter function by name or by passing an array of candidate names. axios uses this internally to select the best available adapter for the current environment.
getAdapter(adapters: string | string[]): AxiosAdapter;
import { getAdapter } from 'axios';
// Get the fetch adapter explicitly
const fetchAdapter = getAdapter('fetch');
// Get the best available adapter from a priority list
const adapter = getAdapter(['fetch', 'xhr', 'http']);
mergeConfigMerges two axios config objects together, applying the same deep-merge strategy that axios uses internally when combining defaults with per-request options. Later values take precedence.
mergeConfig<T>(config1: AxiosRequestConfig<T>, config2: AxiosRequestConfig<T>): AxiosRequestConfig<T>;
import { mergeConfig } from 'axios';
const base = { baseURL: 'https://api.example.com', timeout: 5000 };
const override = { timeout: 10000, headers: { 'X-Custom': 'value' } };
const merged = mergeConfig(base, override);
// { baseURL: "https://api.example.com", timeout: 10000, headers: { "X-Custom": "value" } }
HttpStatusCodeAn object that contains a list of HTTP status codes as named constants. Use this to write readable conditionals instead of bare numbers.
import axios, { HttpStatusCode } from 'axios';
try {
const response = await axios.get('/api/resource');
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response?.status === HttpStatusCode.NotFound) {
console.error('Resource not found');
} else if (error.response?.status === HttpStatusCode.Unauthorized) {
console.error('Authentication required');
}
}
}
VERSIONThe current version of the axios package. This is a string that represents the version number of the package. It is updated with each release of the package.