Creating APIs Part 8: Validation

Performance is king (well, after accuracy) in APIs. Sending a request to the Database only to discover that the request is invalid is a waste of resources. Thus, we want to validate the request as soon as it hits the endpoint.

FluentValidation is a great tool for creating validators. It installs as a NuGet package. Also grab the version for ASP.Net.

To get going, add a using statement. 

Using FluentValidation 

Next, create a class that derives from AbstractValidator. 

public class CarNotDeletedValidator : AbstractValidator<Car> 

This example uses the Car class from my forthcoming book Creating .NET APIs with C#.

Put your validation rules in the constructor. Each rule is created by using the keyword RuleFor and a lambda expression that indicates which property you want to validate and the validation rule.

using Cars.Data.DTOs; 
using FluentValidation;
namespace Cars.Validators
{ 
    public class CarNotDeletedValidator : AbstractValidator<CarDto> 
    { 
        public CarNotDeletedValidator() 
        { 
            RuleFor(x => x.Is_Deleted).Equal("0"); 
        } 
    } 
}
The Equal operator is one of many that you can find at the FluentValidation documentation page: https://docs.fluentvalidation.net/en/latest/built-in-validators.html

We’ll test the data and then either compare it to what is valid and return an error if appropriate, or, more commonly, we’ll throw an exception if the data fails validation. 

Assuming that it passes validation we can continue to the Database. If however it fails, we can return a meaningful error to the sender.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

2 Responses to Creating APIs Part 8: Validation

  1. Hairstyles says:

    Admiring the commitment you put into your blog and detailed information you present. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed material. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  2. Health says:

    Today, with all the fast life-style that everyone leads, credit cards have a huge demand throughout the market. Persons from every arena are using credit card and people who aren’t using the card have lined up to apply for one. Thanks for giving your ideas in credit cards.

Leave a Reply

Your email address will not be published. Required fields are marked *