Unified API responses in .NET projects streamline communication between applications, emphasizing consistency and clarity in software development. This readme delineates the advantages and procedural steps involved in implementing unified API responses.
A Unified API Response is essentially a standardized format for the responses generated by API endpoints. Regardless of the outcome of the request, the response adheres to a uniform structure, usually enclosed within a Result object. This uniformity enhances clarity and streamlines processing for developers and clients alike.
- which encapsulates the message.
- You can easily change from String to Error and vice versa using Implicit Conversion.
public class Error
{
public Error(string message)
{
Message = message;
}
public string Message { get; }
public static Error None => new(string.Empty);
public static implicit operator Error(string message) => new(message);
public static implicit operator string(Error error) => error.Message;
}
- will serve as the response object.
public class Result
{
public Result(bool isSuccess, Error error)
{
IsSuccess = isSuccess;
Error = error;
}
public bool IsSuccess { get; }
public Error Error { get; }
public static Result Success() => new(true, Error.None);
public static Result Failure(Error error) => new(false, error);
public static Result<T> Success<T>(T data) => new(true, Error.None, data);
public static Result<T> Failure<T>(Error error) => new(false, error, default);
}
- Contains Property Called Data Which Return Result with Data
public class Result<T> : Result
{
public T? Data { get; }
public Result(bool isSuccess, Error error, T? data) : base(isSuccess, error)
{
Data = data;
}
}
- Extention Metod based on Result Class To to handle the Success and Failure Cases
public static class ResultExtensions
{
public static T Match<T>(this Result result,
Func<T> onSuccess,
Func<Error, T> onFailure)
{
return result.IsSuccess ?
onSuccess() :
onFailure(result.Error);
}
}