Lesson 30 of 158 – API Error Response
30%

API Error Response

An API Error Response is the information returned by a server when an API request cannot be completed successfully. A good REST API should return a clear HTTP status code and a useful JSON error response.

When a React Native application communicates with a PHP REST API, error responses help the mobile application understand what went wrong and decide what should be displayed to the user.

Note: An API error response normally contains two important parts: an appropriate HTTP status code and a useful response body.

1. What is an API Error Response?

An API error response is a response returned by the server when it cannot successfully complete the requested operation.

For example:


404 Not Found

{
    "success": false,
    "message": "Student not found"
}

2. Why are Error Responses Important?

A mobile application needs to know why an API request failed. A clear error response makes it easier to handle problems correctly.

For example, the application may need to show:

  • Invalid login details
  • Student not found
  • Required field missing
  • Unauthorized request
  • Server error

3. Basic Error Response

A simple API error response can contain a success flag and message.


{
    "success": false,
    "message": "Student not found"
}

The false value indicates that the operation was not successful.

4. Error Response with HTTP Status

An API should also use an appropriate HTTP status code.


HTTP/1.1 404 Not Found
Content-Type: application/json

{
    "success": false,
    "message": "Student not found"
}

The status code and JSON body work together to describe the error.

5. Common API Error Status Codes

Status Code Meaning
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
405 Method Not Allowed
422 Unprocessable Content
500 Internal Server Error

6. 400 Bad Request

The 400 Bad Request status can be used when the server cannot process the request because the request is invalid.


HTTP/1.1 400 Bad Request

{
    "success": false,
    "message": "Invalid request"
}

7. 401 Unauthorized

The 401 Unauthorized status is commonly used when authentication credentials are missing or invalid.


HTTP/1.1 401 Unauthorized

{
    "success": false,
    "message": "Authentication required"
}

This is commonly encountered when working with token-based authentication.

8. 403 Forbidden

The 403 Forbidden status indicates that the server understood the request but refuses to authorize the requested operation.


HTTP/1.1 403 Forbidden

{
    "success": false,
    "message": "Access denied"
}

This can be useful when implementing role-based authorization.

9. 404 Not Found

The 404 Not Found status can be returned when a requested resource does not exist.


HTTP/1.1 404 Not Found

{
    "success": false,
    "message": "Student not found"
}

For example, a request for /api/students/1000 may return 404 if student 1000 does not exist.

10. 405 Method Not Allowed

The 405 Method Not Allowed status can be used when the HTTP method is not supported by an endpoint.


HTTP/1.1 405 Method Not Allowed

{
    "success": false,
    "message": "Method not allowed"
}

11. 422 Validation Error

A 422 Unprocessable Content response can be used when the request is syntactically valid but contains data that cannot be accepted by the application.


HTTP/1.1 422 Unprocessable Content

{
    "success": false,
    "message": "Validation failed"
}

12. 500 Internal Server Error

The 500 Internal Server Error status indicates that the server encountered an unexpected condition while processing the request.


HTTP/1.1 500 Internal Server Error

{
    "success": false,
    "message": "Internal server error"
}

Production APIs should avoid exposing sensitive server details in error responses.

13. Validation Error Response

A validation response can contain details about individual fields.


{
    "success": false,
    "message": "Validation failed",
    "errors": {
        "name": "Name is required",
        "email": "Email is invalid"
    }
}

This structure is useful for displaying field-specific messages in a mobile form.

14. Multiple Validation Errors

An API may need to return more than one validation error.


{
    "success": false,
    "message": "Please correct the errors",
    "errors": {
        "name": "Name is required",
        "email": "Email is required",
        "mobile": "Mobile number is invalid"
    }
}

15. Error Response with Error Code

An application can also include an application-specific error code.


{
    "success": false,
    "code": "STUDENT_NOT_FOUND",
    "message": "Student not found"
}

The application-specific code can help the mobile application handle known error conditions.

16. Error Response with Details

Additional details can be included when they are useful and safe to expose.


{
    "success": false,
    "message": "Unable to create student",
    "details": "Email already exists"
}

Sensitive internal information such as database credentials or stack traces should not be returned to clients.

17. Error Response in PHP

PHP can create a JSON error response using http_response_code() and json_encode().


http_response_code(404);

header(
    "Content-Type: application/json"
);

echo json_encode([
    "success" => false,
    "message" => "Student not found"
]);

exit;

18. PHP Validation Error

A PHP API can validate required fields before processing a request.


if (empty($name)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Name is required"
    ]);

    exit;
}

19. PHP Error Response for Database Failure

If a database operation fails unexpectedly, the API can return a server error response.


http_response_code(500);

echo json_encode([
    "success" => false,
    "message" => "Unable to process request"
]);

exit;

Detailed database errors should normally be logged on the server rather than exposed to the mobile application.

20. Handling API Errors with Fetch

React Native can check the HTTP response before processing the result.


const response = await fetch(
    "https://example.com/api/students/100"
);

const result = await response.json();

if (!response.ok) {

    console.log(result.message);

} else {

    console.log(result.data);

}

The response.ok property indicates whether the HTTP status is in the successful range.

21. Handling API Errors with Axios

Axios provides an error object when an HTTP request fails.


try {

    const response = await axios.get(
        "https://example.com/api/students/100"
    );

    console.log(response.data);

} catch (error) {

    console.log(
        error.response?.data
    );

}

The server's JSON error response can be accessed through the Axios error response data when available.

22. Showing Error Message in React Native

The error message returned by the API can be displayed to the user.


if (!response.ok) {

    const result =
        await response.json();

    Alert.alert(
        "Error",
        result.message
    );

    return;
}

This allows the application to show a useful message instead of a generic failure message.

23. Error Response with TypeScript

TypeScript can describe the structure of an API error.


interface ApiError {
    success: boolean;
    message: string;
    code?: string;
    errors?: {
        [key: string]: string;
    };
}

This makes error handling more predictable in a TypeScript React Native application.

24. Authentication Error Response

An API can return a clear error when authentication fails.


HTTP/1.1 401 Unauthorized

{
    "success": false,
    "message": "Invalid credentials"
}

This can be used by a login screen to inform the user that the provided credentials were not accepted.

25. Common API Error Response Mistakes

  • Returning the wrong HTTP status code.
  • Returning HTML instead of JSON from a JSON API.
  • Using unclear error messages.
  • Exposing database errors to users.
  • Exposing passwords or tokens in error responses.
  • Returning inconsistent error structures.
  • Not validating input.
  • Not handling errors in the mobile application.

26. Good API Error Response Structure

A practical error response can contain a small set of consistent properties.


{
    "success": false,
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "errors": {
        "email": "Email is required"
    }
}
Property Purpose
success Indicates that the operation failed.
code Identifies the application-specific error.
message Provides a readable explanation.
errors Provides field-specific validation errors.

27. Testing Error Responses in Postman

Postman is useful for testing API errors before connecting the API to a React Native application.

  1. Open Postman.
  2. Enter the API URL.
  3. Use an invalid ID or invalid data.
  4. Send the request.
  5. Check the HTTP status code.
  6. Check the JSON response.
  7. Verify that the error message is clear.

28. Complete API Error Flow


React Native
      ↓
API Request
      ↓
PHP REST API
      ↓
Validate Request
      ↓
Error Found
      ↓
HTTP Status Code
      ↓
JSON Error Response
      ↓
React Native
      ↓
Display Error Message

29. Complete Student API Error Example

Suppose the mobile application requests a student that does not exist.


GET /api/students/999

HTTP/1.1 404 Not Found
Content-Type: application/json

{
    "success": false,
    "code": "STUDENT_NOT_FOUND",
    "message": "Student not found"
}

React Native can check the status and display the message:


if (!response.ok) {

    const error =
        await response.json();

    Alert.alert(
        "Error",
        error.message
    );
}

30. Complete API Error Response Concept

A good REST API should return meaningful errors using appropriate HTTP status codes and a consistent JSON response structure.


HTTP/1.1 400 Bad Request
Content-Type: application/json

{
    "success": false,
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "errors": {
        "name": "Name is required",
        "email": "Email is invalid"
    }
}

The React Native application can read this response, determine what went wrong, and display an appropriate message to the user.

Remember the basic pattern:


HTTP Status Code
       +
JSON Error Response
       ↓
Clear Error Handling

📌 Key Points

  • An API error response is returned when an operation cannot be completed successfully.
  • Use appropriate HTTP status codes for different error situations.
  • 400 can represent a bad request.
  • 401 can represent missing or invalid authentication.
  • 403 can represent a forbidden operation.
  • 404 can represent a resource that was not found.
  • 405 can represent an unsupported HTTP method.
  • 422 can represent validation or semantic input problems.
  • 500 can represent an unexpected server-side error.
  • JSON is commonly used for REST API error responses.
  • A success property can indicate whether the operation succeeded.
  • A message property should clearly explain the error.
  • An errors property can contain field-specific validation errors.
  • Server-side sensitive information should not be exposed to clients.
  • React Native should handle API errors and show appropriate messages.
  • Postman can be used to test error responses.

🧠 Quick Quiz

Question: Which HTTP status code is commonly used when a requested resource is not found?