Question: WebApi different DTO for Get and Post

Question

WebApi different DTO for Get and Post

Answers 1
Added at 2017-01-02 13:01
Tags
Question

Is it ok to have different DTO's for GET and POST actions ?

The reason for this is there is usually a vast difference between these two data models.

For example:

My POST would look like this:

/// <summary>
/// Add new user
/// </summary>
/// <param name="item">User data</param>
/// <returns>Newly added user id</returns>
[HttpPost]
public IHttpActionResult Post([FromBody] UserDto item)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var model = _mapper.Map<User>(item);

    int itemid = _usersRepository.Insert(model);

    return Ok(itemid);
}

public class UserDto
{
    private string _password;

    [Required]
    [StringLength(100, ErrorMessage = "Name {0} must consist of at least {2} letters.", MinimumLength = 6)]
    public string Name { get; set; }

    [Required]
    public string ExternalName { get; set; }

    [Required]
    public bool Active { get; set; }

    [Required]
    public string Password
    {
        get { return _password; }
        set { _password = value.Hash(); }
    }
}

and my GET would look like this:

/// <summary>
/// Get all users
/// </summary>
/// <returns>Users list</returns>
[HttpGet]
[ResponseType(typeof(List<UserInfoDto>))]
public IHttpActionResult Get()
{
    IList<UserInfoDto> values = _usersRepository.SelectAll();

    if (values == null || !values.Any())
        return Ok();

    return Json(new { collection = values });
}

public class UserInfoDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string ExternalName { get; set; }

    public bool Active { get; set; }
}

The reason I'd do this is that I don't need Id when POSTing a resource but Password is necessary. It is reversed when using GET.

Is this the correct approach when using WebApi (Creating different Dtos for responses and requests)? Or is there some other way to do this ?

Answers to

WebApi different DTO for Get and Post

nr: #1 dodano: 2017-01-02 14:01

Is it ok to have different DTO's for GET and POST actions ?

There is nothing wrong with having different dto's for different actions.

If the api is being used by 3rd parties you would want to make sure that it is well documented.

Is this the correct approach when using WebApi?

Whether this is correct approach or not is a matter of opinion. Expose or accept the necessary information for the system to perform as intended.

Each action could use its own unique dto. Doesn't mean that it should. You want to make sure you are not leaking more information than is necessary.

Source Show
◀ Wstecz