ASP.NET Core 2.2 REST API #6 — Updating Resources with PUT

Theodoros Ntakouris
2 min readJul 23, 2019

--

Up Next: Managing Entities with Entity Framework Core

There are 2 ways to update a resource:

  • Fully update
  • Partially update

In this post, we are going to fully update the resource: Change everything, but leave the id being the same.

We are going to use the verb PUT in order to do that. Just add another method to our IPostService : bool UpdatePost(Post postToUpdate) . All that does is, check if the posts exists, and if it does, update everything (it’s name for now). Updating the post is just by getting it’s index and replacing it with the postToUpdate object. We are going to use a database for all these CRUD operations in a later tutorial.

The next step is — you guessed it — create a new endpoint

[HttpPut(ApiRoutes.Posts.Update)]
public IActionResult Update([FromRoute] postId, [FromBody] UpdatePostRequest request)

The UpdatePostRequest contract is just used to enumerate all the members that are going to change, thus only a string name .

We can use those 2 parameters to create a new post object by using the postId from the route parameter and the name from the contract request located in the body.

We are returning NotFound when the post update operation fails. For now, it just means that the given post id does not exist.

Our API works as expected

Successful Update

NotFound (bad id)

Up Next: Managing Entities with Entity Framework Core

Code is available on Github and the instructional videos are located on YouTube.

Keep Coding

--

--

No responses yet