Differences in models for GET and POST requests

869 views Asked by At

I am creating a Web API using Asp .NET Core and am having troubles figuring out how to create my data models.

Lets say I get the following model from the backend:

public class Author : AuditEntity
{
    public int Id { get; set; }

    [StringLength(45)]
    public string Name { get; set; } = null!;

    public Label DescriptionLabel { get; set; } = null!;

    public int DescriptionLabelId { get; set; }

    public ICollection<Quote> Quotes { get; } = new List<Quote>();
}

When we get a GET request we use the following trivial model:

public class Author
{
    public Author() {}

    public Author(Core.Entities.Author model)
    {
        Id = model.Id;
        Name = model.Name;
        DescriptionLabel = new Label(model.DescriptionLabel);
    }

    public int Id { get; set; }

    public string Name { get; set; } = null!;

    public Label DescriptionLabel { get; set; } = null!;
}

Important here is that the DescriptionLabel can not be null. But if I want to process a POST or PUT request, I will want to be able to allow that the DescriptionLabel is null. So my question is, should I just use the GET model and make the label there nullable or do I have to create a new model just for the label to be nullable there?

what are some standards for small differences in the models for Getting and Posting data to a web api?

1

There are 1 answers

0
Max On BEST ANSWER

Short example on separate input output classes inside controller. Key to note also is that each controller class have only one method. This is to keep it more clean. I find this approach simple and easy to read.

[ApiController]
[Route("[controller]")]
[AllowAnonymous]
public class SignIn : ControllerBase
{
    [HttpPost]
    public Output Post(Input input)
    {
        var user = Users.ValidateLoginCredentials(input.Email, input.Password);
        if (user != null)
        {
            return new Output
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                JWT = GenerateJWT(user)
            };
        }
        return null;
    }

    public class Input
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class Output
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string JWT { get; set; }
    }
}