tyrion
tyrion

Reputation: 742

How to design retrieving only specific properties with REST API via GET

I need to define a REST API which is supposed to take the object's unique identifier and return back the content. The content is retrieved from the database and is of JSON type. So, I have a REST URL like this -

GET /data/{typename}/{objectid}

This would return the entire object content.

However, the content of the object could be large in size and so caller may like to specify only some or few of the properties to be sent as a response. The natural thought that comes to me is to add a BODY to the GET API where user could specify the list of property names on that object to be retrieved. But on doing some further research, it appears that a GET API with BODY is not recommended. The other option that I can think of is to pass the property names in query string -

GET /data/{typename}/{objectid}?property=prop1&property=prop2...

But the list could easily become large.

Any suggestion on how should my API look like? Do I have to use POST?

Upvotes: 6

Views: 18345

Answers (2)

Amr Eladawy
Amr Eladawy

Reputation: 4358

Technically, using POST will work but is not preferred. If you are reading, use GET. Facebook, for example, has a similar use case where the /me endpoint has many filters, and the call is GET.

The final URL would be, /me?fields=id,name,about,age_range,devices,currency,education

You can try it yourself from here, https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me%3Ffields%3Did%2Cname%2Cabout%2Cage_range%2Cdevices%2Ccurrency%2Ceducation&version=v2.8

I recommend reading more about GraphAPI https://developers.facebook.com/docs/graph-api/overview/ and GraphQL https://graphql.org/

Upvotes: 5

online Thomas
online Thomas

Reputation: 9381

I would recommend using POST, because GET has a length limit. What is the maximum length of a URL in different browsers?

otherwise you could make your query string look like this (for array) so close :)

GET /data/{typename}/{objectid}?property[]=prop1&property[]=prop2...

Upvotes: 0

Related Questions