DEV Community

Cover image for API Validation & Error Handling: Building Reliable Backends That Don't Break in Production
Ayesha Ahmed
Ayesha Ahmed

Posted on

API Validation & Error Handling: Building Reliable Backends That Don't Break in Production

A successful API request starts long before the backend processes the data.

One invalid field, missing parameter or unexpected server response can break an entire application if validation and error handling aren’t designed properly.

Let’s understand two important parts of reliable backend engineering: API Validation & Error Handling.

Topic: API Validation & Error Handling
Category: WEB + BACKEND ENGINEERING

What Is API Validation?

API validation means checking incoming request data before using or processing it.

Imagine you’re building an e-commerce application.

A customer sends a request to place an order:

{
"productId": 101,
"quantity": -5,
"email": "invalid-email"
}

Should the backend accept this request?

Absolutely not.

The quantity is negative, and the email format is invalid.

The backend should validate the incoming data before performing any business operation.

Why Is API Validation Important?

Without proper validation, applications can experience:

• Invalid database records.
• Unexpected application behavior.
• Incorrect calculations.
• Security vulnerabilities.
• Failed business operations.
• Inconsistent data.

For example, imagine a payment API accepting a negative payment amount because the backend doesn’t validate the request.

That’s not just a coding issue. It’s a serious business risk.

Never assume that data coming from Flutter, React or any other frontend is automatically valid.

Common Types of API Validation

Here are some important validations used in real applications.

Required Field Validation

Check whether mandatory fields are provided.

Example:

{
"name": "",
"email": "user@example.com"
}

If the name is required, the backend should reject the request.

Data Type Validation

Make sure values have the expected data types.

For example:

{
"quantity": "five"
}

If quantity must be an integer, this request should fail validation.

Format Validation

Check whether values follow the expected format.

Examples:

• Valid email format.
• Correct phone number format.
• Valid date format.

Range Validation

Check whether values fall within acceptable limits.

Example:

{
"age": 250
}

If the application requires an age between 18 and 100, the backend should reject this value.

Business Rule Validation

Some validations depend on the application’s business logic.

For example:

• A customer cannot order an unavailable product.
• A seller cannot update another seller’s product.
• A user cannot withdraw more money than their available balance.

These checks are just as important as basic field validation.

Implementing Validation in Node.js / Express

Let’s use Express with the express-validator package.

First, define validation rules:

const { body, validationResult } =
require('express-validator');

app.post(
'/api/users',

[
body('name')
.trim()
.notEmpty()
.withMessage('Name is required'),

body('email')
  .isEmail()
  .withMessage('Enter a valid email'),

body('password')
  .isLength({ min: 8 })
  .withMessage('Password must be at least 8 characters')
Enter fullscreen mode Exit fullscreen mode

],

(req, res) => {
const errors = validationResult(req);

if (!errors.isEmpty()) {
  return res.status(422).json({
    success: false,
    errors: errors.array()
  });
}

return res.status(201).json({
  success: true,
  message: 'User created successfully'
});
Enter fullscreen mode Exit fullscreen mode

}
);

What’s happening here?

The backend receives the request.

Validation rules check the submitted information.

Invalid data produces validation errors.

The backend returns 422 Unprocessable Content.

Valid data can proceed to the next processing step.

This is a simplified example. A production endpoint should also securely hash passwords, check for duplicate accounts and handle database failures.

What Is API Error Handling?

Validation checks whether incoming data is acceptable.

Error handling manages problems that occur while processing requests.

For example:

A user submits valid login credentials, but the database connection fails.

Or a customer requests a product that no longer exists.

Or an external payment service doesn’t respond.

These situations need proper error handling.

The application shouldn’t crash or return confusing messages.

Understanding Common API Error Responses

Here are some HTTP status codes you’ll frequently handle.

400 Bad Request

The request is malformed or invalid.

401 Unauthorized

Valid authentication credentials are missing or invalid.

403 Forbidden

The authenticated user doesn’t have permission.

404 Not Found

The requested resource doesn’t exist.

409 Conflict

The request conflicts with the current resource state.

422 Unprocessable Content

The request is understood, but its data fails validation or semantic rules.

429 Too Many Requests

The client has exceeded a rate limit.

500 Internal Server Error

An unexpected problem occurred on the server.

503 Service Unavailable

The service is temporarily unable to handle requests.

Choosing appropriate status codes makes communication between frontend and backend more predictable.

Handling Errors in Express

Instead of writing repetitive error-handling logic inside every route, Express supports centralized error-handling middleware.

Example:

app.use((err, req, res, next) => {
console.error('API Error:', err);

const statusCode = err.statusCode || 500;

res.status(statusCode).json({
success: false,
message:
statusCode === 500
? 'Something went wrong'
: err.message
});
});

Now errors can be passed to a common handler.

For example:

app.get('/api/products/:id', async (req, res, next) => {
try {
const product = await findProduct(req.params.id);

if (!product) {
  const error = new Error('Product not found');
  error.statusCode = 404;
  throw error;
}

res.status(200).json(product);
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
next(error);
}
});

The error-handling middleware receives the error and returns a consistent response.

In production, error logging should capture useful diagnostic information without exposing passwords, tokens, stack traces or internal system details to clients.

Returning Consistent API Responses

A common backend problem is returning completely different response structures from different endpoints.

For example:

One endpoint returns:

{
"message": "Invalid email"
}

Another returns:

{
"error": "Something went wrong"
}

And another returns plain text.

This makes frontend integration harder.

A consistent response structure is easier to maintain.

For example:

Successful response:

{
"success": true,
"message": "Product created successfully",
"data": {
"id": 101,
"name": "Wireless Mouse"
}
}

Error response:

{
"success": false,
"message": "Validation failed",
"errors": [
{
"field": "quantity",
"message": "Quantity must be greater than zero"
}
]
}

Now Flutter or any other frontend can handle responses using a predictable structure.

Handling API Errors in Flutter

Backend validation and error handling are only part of the process.

The Flutter application also needs to handle responses properly.

Let’s use Dio:

try {
final response = await dio.post(
'/api/orders',
data: {
'productId': 101,
'quantity': 2,
},
);

print('Order created successfully');

} on DioException catch (e) {
final statusCode = e.response?.statusCode;

if (statusCode == 422) {
print('Please check the submitted information');

} else if (statusCode == 401) {
print('Your session has expired');

} else if (statusCode == 500) {
print('Server error. Please try again later');

} else {
print('Unable to complete your request');
}
}

In a production Flutter application, I prefer handling API errors inside the repository or service layer and exposing meaningful states to the UI.

The UI should display useful messages rather than technical exceptions.

For example:

Backend response:
“Quantity must be greater than zero.”

Flutter message:
“Please enter a valid quantity.”

This creates a better user experience.

Validation vs Error Handling

These two concepts work together, but they are not the same.

API Validation:
Checks whether incoming data meets the required rules.

Error Handling:
Manages failures that occur during request processing.

Example:

A customer submits an order with a quantity of -5.

Validation rejects the request.

The backend returns a 422 response.

Flutter displays the validation message.

That’s how both concepts work together.

Common Mistakes Developers Should Avoid

When building production APIs, watch out for these mistakes:

• Trusting frontend validation without backend validation.

• Accepting unexpected data types.

• Returning HTTP 200 for failed operations.

• Exposing database errors directly to users.

• Ignoring missing or invalid fields.

• Writing duplicate error-handling logic across controllers.

• Forgetting to handle database connection failures.

• Not validating user permissions and resource ownership.

• Retrying every failed request without considering whether the operation is safe to repeat.

• Returning inconsistent response structures.

These mistakes can create serious problems when real users start interacting with an application.

Real-World Example: E-commerce Order API

Imagine a Flutter application connected to a Node.js backend and PostgreSQL database.

A customer places an order.

The backend needs to:

Validate the customer ID and product information.

Check whether the user is authenticated.

Verify product availability.

Validate the requested quantity.

Calculate the order total using trusted backend data.

Create the order using a database transaction.

Return a meaningful response.

What if the product is out of stock?

Return an appropriate error.

What if the customer sends an invalid quantity?

Reject the request.

What if the database fails?

Handle the exception, log the details and return a safe server error.

What if the connection times out after the order was created?

Verify the order status before retrying to avoid creating duplicate orders. Idempotency keys can help protect critical operations.

This is why validation and error handling should be part of backend architecture from the beginning.

My Approach to Reliable API Development

When building APIs, I focus on five things:

• Validate every incoming request on the backend.

• Keep validation rules separate and reusable where appropriate.

• Use meaningful HTTP status codes.

• Maintain consistent API response structures.

• Handle unexpected failures without exposing sensitive information.

I also test both successful and unsuccessful scenarios using tools such as Postman before connecting the endpoints to the Flutter application.

Because an API isn’t production-ready simply because it returns the expected data once.

It must also behave correctly when users send invalid information, services fail or unexpected situations occur.

Final Takeaway

API validation protects the quality of incoming data.

Error handling protects the application when something goes wrong.

Together, they make backend systems more predictable, secure and reliable.

Whether you’re developing a Flutter application, CRM, ERP, SaaS platform or e-commerce system, these are not optional improvements.

They are essential parts of professional backend engineering.

💬 When building APIs, which area do you focus on most: request validation, centralized error handling or consistent API responses?

Share your experience and follow AyeshaAppDev for practical Backend Engineering, REST APIs, Flutter Development and real-world Software Engineering insights.

AyeshaAppDev | Software Engineer

Top comments (0)