Saturday 13 July 2019

Basic REST stuff

I have a very limited knowledge (being optimistic) about REST API's (I mean, using the right url's, the HATEOAS thing...) and the other day I came across a couple of points that I'll share.

I was doing a GET request and the last parameter was a decimal value, something like this:

http://myserver.org/documents/docId/version

http://myserver.org/documents/a123bb/1.1

The above would give a server error (thrown by the http server itself, not by the ASP.NET Web API controller). The problem is because finishing the url with a ".1" the http server was interpreting that I was requesting a file. You can easily fix this by adding a "/" at the end, I mean:

http://myserver.org/documents/a123bb/1.1/

The next issue I came across was with an optional parameter not placed at the end of the url. I want the children of a document for a given version, but the version parameter is optional, as if missing we'll use the last available document. I wanted to use something like this:

http://myserver.org/documents/a123bb/1.1/children

http://myserver.org/documents/a123bb/children

[HttpGet]
[Route("{docId}/{version}/children")]
public HttpResponseMessage GetDocumentChildren(string docId, string version = null){}

The above would not work for the second url. The controller would not understand that version was missing there. In the end I had to add a second route to the controller, so I ended up with this:

[HttpGet]
[Route("{docId}/{version}/children")]		
[Route("{docId}/children")]
public HttpResponseMessage GetDocumentChildren(string docId, string version = null){}	

No comments:

Post a Comment