Should I create DTO to remove id from object in put method?

Viewed 575

I wanna create simple API, for example - todo API.

Created model

public class Todo
{
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Completed { get; set; }
}

And than in code, I wanna create some methods. So I go to put method, start writing:

[HttpPut("{id}")]
public IActionResult Put(Todo todo, int id)
{
    ...
}

And than I don't know if I should check if id from URL is same as id from todo or I should ignore id from todo or create TodoUpdateDTO without id.

I know what whatever I would do - it will just work, but what is a good practice in .NET Core?

2 Answers

I would keep the id in my method, so what you have written here seems correct:

[HttpPut("{id}")]
public IActionResult Put(int id)
{
...
}

However regarding your class, I would usually use two classes like this:

public class TodoBase
{
    public string Title { get; set; }
    public bool Completed { get; set; }
}

And:

public class Todo: TodoBase
{
    public int Id { get; set; }
}

So it would be better, in some methods like Put, you use the TodoBase class:

[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]TodoBase todo)
{
...
}

So in case you want to create a new entity in which it's Id is auto generated, you don't have to provide the Id in your request anymore and you can simply use the base class, but for methods like Get, you can use the Todo class as it will be retrieved from the db and it should contains Id already.

I would create a separate PutTodoRequest class for the HttpPut, just because I might need to add validation logic for the request payload.

public class PutDotoRequest
{
    [Required]
    public string Id { get; set; }

    [Required]
    public string Title { get; set; }
    
    [Required]
    public bool? Completed { get; set; }
}

[HttpPut("{id}")]
public IActionResult Put([FromBody] PutDotoRequest request)
{
    if (!ModelState.IsValid)
        return BadRequest();

    // code
}
Related