sunebrodersen
sunebrodersen

Reputation: 309

Parameters etc in my REST service

Im building a REST webservice and have of course done some research but are still left with some unanswered questions. My service will be returning JSON only for starters.

1.I have settled on using queryparameters for my GET, like

/api/users/54354/?fields=name,age 

for getting the name and age from the user with id=54354. There seems to be big discussions on what approch to take but this seeems to be a commen way. For my POST, PUT I of course use the body for theese parameters. What are your oppinion on this approch and please argue if you see it to be solved differently.

2: When using GET (or POST and PUT for that matter) how would you specify queries with operators like "lastname starts with 'Pe'" or "Age between 10 and 20"? Im considering if it would make sense to put the full query in an object of some kind. E.g.

api/users/?filter={'name':{'startsWith':'Pe'},'Age':{'Min':10},'Age':{'Max:'20}}

This kind of apply the JSON syntax to queryies, but im not sure if there is another "best-practice" approch to this. The above would require a parser / verifier in the service to verify valid filters etc.

3: Last thing would be how to apply AND and OR operations to it. I guess it could work in a JSON object too.

Hope some of you guys can give some feedback on this issue :)

Upvotes: 1

Views: 173

Answers (1)

mtsz
mtsz

Reputation: 2855

  1. I wonder if you should really retrieve separate fields. Since you the user represents a resource you should get the whole resource and extract the needed information from the json in your client. When you have attached resources to the user which are too big to be transferred per query they should be modelled as subresources (/api/users/54354/subresource).

  2. Using JSON-syntax in queries does not seem to me as best practice, as curly braces count as unsafe characters which should be encoded. You could specify the query with /api/users?nameStartsWith=pe&age=10-20. The question mark should follow the identifier of the resource and not the slash. The ampersand denotes a logical AND and the minus denotes a range.

  3. It depends how complex your queries gonna be. You could uses value lists after the = like startWithName=pe,foo,bar to enable disjunctions there. This should even work with the ranges age=10-20,33,40-50. You could use & as mentioned for AND and + for OR (+ is often used as AND in APIs, but well...). When you include parentheses you could nest such expressions... if you need to. But i seriously doubt you should do this since there are dedicated search query languages for such complex queries.

Upvotes: 1

Related Questions