Axios Response Schema — Complete Guide with Examples
In this tutorial, you'll learn about the Axios response schema. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Axios response schema defines the structure of every successful response object, containing data, status code, status text, headers, the original request config, and the underlying request object.
What You'll Learn
By the end of this tutorial, you'll understand each property of the response object, extract data efficiently, read response headers, access the request config for debugging, and handle pagination metadata.
Why It Matters
Every Axios response carries more than just the data. Status codes tell you if the request succeeded. Headers contain pagination info, rate limits, and Caching directives. The config property helps debug what was actually sent.
Real-World Use
Durga Antivirus Pro reads response headers to determine Rate Limiting status. When the X-RateLimit-Remaining header drops below 10, the app queues remaining requests. Response config helps debug failed signature update requests.
Where This Fits in Your Learning Path
flowchart LR
A["Request Configuration"] --> B["**Response Schema**"]
B --> C["Transform Data"]
C --> D["Cancellation"]
D --> E["Axios Advanced"]
style B fill:#f97316,stroke:#c2410c,color:#fff
style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
style E fill:#22c55e,stroke:#16a34a,color:#fff
The Full Response Object
Every successful Axios request returns a response object with these properties.
const response = await axios.get('https://api.example.com/users/1')
console.log(response.data) // The server response body (auto-parsed)
console.log(response.status) // HTTP status code (e.g., 200)
console.log(response.statusText) // HTTP status text (e.g., "OK")
console.log(response.headers) // Response headers as an object
console.log(response.config) // The Axios request configuration that was used
console.log(response.request) // The XMLHttpRequest or Node.js request object
Expected output: Each property reveals a different aspect of the HTTP response. data contains the parsed JSON body, status is 200, and headers is an object with all response headers.
Extracting Data with Destructuring
The most common pattern is extracting only the data property.
// Destructure only what you need
const { data } = await axios.get('/api/users')
console.log(data) // Array of users
// Rename on extraction
const { data: users } = await axios.get('/api/users')
console.log(users) // Array of users
// Multiple properties
const { data, status, headers } = await axios.get('/api/users')
console.log(`Status ${status}:`, data)
Expected output: Destructuring gives you direct access to the specific properties you need without the full response wrapper.
Reading Response Headers
Headers provide metadata about the response.
const response = await axios.get('/api/users')
console.log(response.headers['content-type']) // 'application/json'
console.log(response.headers['x-request-id']) // Server-assigned request ID
console.log(response.headers['x-ratelimit-remaining']) // Rate limit info
console.log(response.headers['x-ratelimit-reset']) // When rate limit resets
console.log(response.headers['cache-control']) // Caching directives
Expected output: Each header property reveals server-side metadata. Content-type tells you the response format. Rate limit headers help manage request frequency.
Accessing the Config Object
The config property shows what was actually sent, useful for debugging.
const response = await axios.get('/api/users', {
params: { page: 2 },
headers: { 'X-Custom': 'value' },
timeout: 5000
})
console.log(response.config.url) // '/api/users'
console.log(response.config.params) // { page: 2 }
console.log(response.config.headers) // Merged headers (includes defaults)
console.log(response.config.timeout) // 5000
console.log(response.config.method) // 'get'
Expected output: The config reflects the final merged configuration including instance defaults, global defaults, and per-request overrides.
Handling Pagination Metadata
Many APIs include pagination info in headers or response body.
async function fetchAllPages(baseUrl) {
let page = 1
let allData = []
let hasMore = true
while (hasMore) {
const response = await axios.get(baseUrl, {
params: { page, limit: 100 }
})
allData = allData.concat(response.data)
// Check pagination headers
const total = parseInt(response.headers['x-total-count'])
const perPage = parseInt(response.headers['x-per-page'])
hasMore = page * perPage < total
page++
}
return allData
}
Expected output: The function iterates through all pages by reading pagination headers and concatenating results until all pages are fetched.
Common Mistakes
1. Forgetting to destructure response.data
// Wrong: response is the whole object
const users = await axios.get('/api/users')
console.log(users) // Response object, not the data
// Correct: extract data
const { data: users } = await axios.get('/api/users')
2. Assuming headers are always lowercase
Axios normalizes header names to lowercase. Access them with lower case: response.headers['content-type'].
3. Modifying response.config after the request
config is frozen after the request. Modifying it has no effect. Create a new config for subsequent requests.
4. Not checking response.status for custom logic
Some APIs return 200 with error codes in the body. Always check both status and response body for comprehensive error handling.
5. Accessing response.request in the browser causing CORS issues
The request property may be null or inaccessible due to CORS policies in the browser.
Practice Questions
What does response.data contain? The response body parsed from JSON into a JavaScript object.
How do you access response headers? Through response.headers as an object. Axios normalizes header names to lowercase.
What is response.config used for? Debugging and logging. It contains the final merged configuration that was used for the request.
Can response.statusText be empty? Yes. Some HTTP/2 responses may have an empty statusText.
How do you handle pagination with headers? Read custom headers like x-total-count and x-per-page from response.headers, then calculate remaining pages.
Challenge
Build a response debugger function that logs the full response schema: data type, status, all headers, config URL, and request time. Use it as a response interceptor for development.
FAQ
Mini Project
Build an API inspector component that displays the full response schema after making a request. Show data (formatted JSON), status with color coding, all headers in a table, and the config used.
async function inspectEndpoint(url, options = {}) {
try {
const startTime = performance.now()
const response = await axios.get(url, options)
const duration = performance.now() - startTime
return {
data: response.data,
status: response.status,
statusText: response.statusText,
headers: response.headers,
config: {
url: response.config.url,
method: response.config.method,
params: response.config.params,
timeout: response.config.timeout
},
duration: Math.round(duration)
}
} catch (error) {
return {
error: true,
message: error.message,
status: error.response?.status,
data: error.response?.data
}
}
}
// Usage
const result = await inspectEndpoint('https://jsonplaceholder.typicode.com/posts/1')
console.log('Status:', result.status, result.statusText)
console.log('Data:', JSON.stringify(result.data, null, 2))
console.log('Headers:', result.headers)
console.log('Took:', result.duration + 'ms')
What's Next
Learn about data transformation:
| Tutorial | What You'll Learn |
|---|---|
| Transform Data | Transform request and response data automatically |
| Cancellation | Cancel in-flight requests with AbortController |
Related topics: HTTP status codes reference, response headers and caching.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro