Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should input DTOs for RESTful endpoints match the output DTOs?

I'm working on a RESTful API and I'm having some trouble wrapping my head around the procedure for supplying input to the API.

Let's say I have a "Person" resource that can be fetched like this: api/person/{id} and returns an object like this:

public class Person
{
    public int Id { get; set; }
    public string Surname { get; set; }
    public string GivenName { get; set; }
    public DateTime DateOfBirth { get; set; }
}

If I want to update that person, should the API be expecting a full Person instance, or is it acceptable to use a separate DTO?

Let's say for example the DateOfBirth cannot be changed, is it considered RESTful to accept this as input:

public class UpdatePersonDto
{
    public string Surname { get; set; }
    public string GivenName { get; set; }
}

This would mean I would have this endpoint api/person/{id} returning Person when using GET, while accepting as input UpdatePersonDto when using PUT. This sounds wrong to me, but I'm not sure if I'm just being paranoid.

So I guess my question sums up to this: Is it suitable to accept a data structure on a given resource endpoint that differs from what that endpoint would return?

like image 397
Nick Coad Avatar asked Aug 04 '15 03:08

Nick Coad


1 Answers

It seems the REST consensus is that when updating using PUT, one supplies the entire entity to replace.

Programmatically, it would work having PUT /person/{id} accepting input which behind the scenes maps to UpdatePersonDTO instead of Person.

The only 'problem' could be that it does go against the general expectation.

A middle-ground solution could be POST (or PUT) /person/{id}/mutables which could accept the UpdatePersonDTO.

Edit: Or parhaps more obviously: PUT /person/{id}/name which takes a PersonName argument containing the two fields.

like image 109
morsor Avatar answered Oct 03 '22 03:10

morsor