Architecture
API Responses
Handling API responses.
Response structure
The response is designed to easily verify the outcome, display messages, and provide access to the main content. It includes the following properties:
success
- A boolean indicating if the request was successful.message
- A string with a user-friendly message suitable for UI feedback.payload
- An object containing the requested endpoint data, or an Error object if the request failed.
This ensures a consistent approach in destructuring the response for managing the results of your API requests.
const { success, message, payload: user = {} } = await createUser({...});
console.log(user.name);
if (message) {
toast(message);
}
Successful response
{
"success": true,
"message": "Cosmos Kramer updated successfully.",
"payload": {
"id": "usr_1234567890",
"name": "Cosmos Kramer",
...
}
}
Error response
{
"success": false,
"message": "Required values are missing or invalid.",
"payload": {
"fields": {
"username": "Required value",
"password": "Cannot be your username"
},
...
}
}
Example response handling
Use the response structure to handle the outcome of your API requests.
const { success, message, payload: user = {} } = await updateUser({name: 'Jerry Seinfeld', email: 'jerry@nbc.com'});
// Do something with the user data...
const errorFields = user?.fields ?? {};
if (message) {
toast(message);
}
Related information
- Errors - Understanding the API error feedback.
- Form validation - How Backstack handles form validation.
- API requests - Making requests to the API.