Neilski Neilski - 1 month ago 5
reST (reStructuredText) Question

Why Include Record Key in WebAPI PUT Parameters

In all the ASP.NET WebAPI examples I have seen for implementing the

HTTP PUT
method, the record's key is passed as a separate parameter to the model updates. For example:

[HttpPut]
public HttpResponseMessage Put(int id, UserEditViewModel model)
{
// Look up existing record
User user = await db.Users.FindAsync(id);
// Apply changes
// user.Name = model.Name;
// Commit updated record to data store
db.SaveChanges();
}


I am curious as to why this approach is used rather than to define the key value on the model and simplify the call?

public HttpResponseMessage Put(UserEditViewModel model)
{
// Look up existing record
User user = await db.Users.FindAsync(model.UserId);
// Apply changes
// user.Name = model.Name;
// Commit updated record to data store
db.SaveChanges();
}


In most cases that I can think of the View will require the
UserId
anyway, so I don't see how/why it would complicated the model from the View's perspective, but I am sure there must be a good reason.

Answer

Depending on what level of RESTfulness we're talking about, I think it might be more about convenience. Looking at Richardson's Maturity Model level 3, the workflow could be something like this:

GET /api/users/{id}

Once the client navigates to a user, the server will have built the link uri, filling it with the unique resource identifier, so it could look something like this:

"api:user-edit": {
  "href": "http://apiname:port/api/user/{id}"
},

So the client will have to just do a

PUT /api/users/{id}

with the appropriate payload (which theoretically should be the resource in full, but more often than not the server will only choose to look at just a couple of fields - almost like a PATCH).

Comments