Retrieve only specific properties with REST GET API - rest

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?

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/

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...

Related

Can regex be used to query a REST API?

There is a free test REST API at https://jsonplaceholder.typicode.com/comments
I've figured out that I can get certain objects by specifying their id like this.
https://jsonplaceholder.typicode.com/comments?id=1
I can also do the same for email. Are more complicated queries possible? What if I wanted to get all objects with ids 1-10, or all objects with a certain word in the body? Could I use something like a logical OR to get all objects with either foo in the name or bar in the body? Can regex be used?
you can use https://jsonplaceholder.typicode.com/comments to get all comments and then filter them as you need. axios only takes a url string. So, yes, you can use regex to build that string.Though you can't get object with id 1-10 or use email instead of id if the API doesn't support it.If the API supports it, you can do it.

Should I use GET or POST REST API Method?

I want to retrieve data about a bunch of resources. Let's say an Array of book id and the response is JSON Array of book objects. I want to send the request payload as JSON to the server.
Should I use GET and POST method?
Note:
I don't want to make multiple GET request for each book ID.
POST seems to be confusing as it is supposed to be used only when the request creates a resource or modifies the server state.
I want to retrieve data about a bunch of resources. Let's say an Array of book id and the response is JSON Array of book objects.
If you are thinking about passing the array of book id as the message body of the HTTP Request, then GET is a bad idea.
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
You should use POST instead
POST seems to be confusing as it is supposed to be used only when the request creates a resource or modifies the server state.
That's not quite right. POST can be used for anything -- see GraphQL or SOAP. But what you give up by using POST is the ability of intermediate components to participate in the conversation.
For example, for cases that are effectively read-only, you would like to use a safe method, because that allows pre-caching optimization, and automated retry of lost responses on an unreliable network. POST doesn't have extra semantic constraints, so you lose out.
What HTTP really wants is that you GET using the URI; this can be done in one of two relatively straightforward ways:
POST the ids to the server, to create a new resource (meaning that the server retains for itself a copy of the list of ids), and receive a new resource identifier back in exchange. Then GET using this new identifier any time you want to know the current representation of the results.
Encode the information you need into the URI itself. Most commonly, this is done using the query part of the URI, although that isn't strictly necessary. The downside here is that if the URI encoded representation of the array of ids is very long, you may have trouble with some implementations that enforce arbitrary URI limits.
There aren't always great answers:
The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.
If I understand correctly, you want to get a list of all of the items in a list, in one pull. This would be possible using GET, as REST returns the JSON it can by default be up to 100 items, and you can get more items if needed by specifying $top.
As far as writing back or to the server, POST would be what your looking for, this to my understanding would need to be one for one.
you are going to use a GET-Request and put your request-data (book-id array) in the data-section of your ajax (or whatever you're going to use) request. See How to pass parameters in GET requests with jQuery

Rest API - Getting one-off information for an object

Here is my example. I have a basic rest api for a Member. Simple CRUD. Project manager says "we need an endpoint that will return the remaining pension amount for that member.
I get this stuff a lot where they want a very specific piece of information about an object.I don't want to include this in the Read request as the calculation can be time consuming. So, how do I do this in a RESTful way??
You could create a new endpoint called Pension, which could have a RemainingAmount property (and probably a RemainingCurrencyIso one, too), and expose that through a link from the Member resource like so:
GET /api/member/{id}/pension
If this is a field of the user object, you could have a separate url param
?fields=RemainingAmount
In the absence of the fields param, you just return the full object.

Design a REST API in which a search request can take parameters for multiple Queries

I have to design a REST API in which a search request can take parameters for multiple Queries ( i.e. when the client make a call using this API, he should be able to send parameters to form multiple queries).
We have an existing API where we are using GET and it takes multiple parameters which together forms a single Query and then this API call returns the response for this query.
e.g. currently I can pass firstName, lastName, age etc in the request and then get back the person.
But now I have to enhance this service(or have a separate service) where I should be able to send parameters like firstName1, lastName1, age1 to search person1 ; firstName2, lastName2, age2 to search person2 and so on.
Should I use POST for the new API and then send list of parameters(params for query1, params for query2 and so on)?
Or is there a better approach.
We are using Spring Boot for REST implementation.
Its better to use POST because GET is good for 2,3 parameter but when you have a set of parameter or object then POST is Good.
The best thing to do here will be do POST and then return a JSON object with all the details of the Person in an array.
That way it will be faster and you would not have to deal with long urls for GET.
Also GET has limitations regarding the length of the request whereas there is no such limitation in case of POST.
It is really hard to give a right answer here. In general sending a GET request does have the advantage that you can leverage caching easily on a HTTP level, e.g. by using products like varnish, nginx, etc. But if you already can forsee that your URL including all params you'll have to send a POST request to make it work in all Browsers.
RESTfull architecture should respect the principle of addressability.
Since multiple users can be accessed through a unique request, then ideally this group of user should get an address, which would identify it as a resource.
However I understand that in the real world, URIs have a limited length (maximum length of HTTP GET request?). A POST request would indeed work well, but we lose the benefit of addressability.
Another way would be to expose a new resource : group,.
Lets suppose that your current model is something like this :
.../users/{id}
.../users/search?{arg1}={val1};{arg2}={val2}
You could eventually do something like :
.../users/groups/
.../users/groups/{id}
.../users/search?group={id}
(explanation below)
then you could split your research in two :
first a POST on .../users/groups/ with, as proposed by other response, a JSON description of the search parameters. This request could scan the .../users/groups/ directory, and if this set of parameters exists, return the corresponding address .../users/groups/{id}. (for performance issues you could for instance define {id} with a first part which would give the number of users requested).
Then you could make a request for this group with a GET with something like this : .../users/search?group={id}.
This approach would be a bit more complex to implement, but is more consistent with the resource oriented paradigm.

REST API Design with many input parameters including collections

I need to design and implement a REST API where users need to pass many input parameters. Out of those input parameters few are collection of an integer, few of them are date strings etc. After getting all these parameters I need to return unique id in the response. What method type (PUT, POST or GET) I should use in order to implement this API? How can I pass all these parameters to the API? I don't want users to format input parameter list into XML or JSON and post as a request body.
I appreciate if anybody can help on this topic.
POST is for creating new resources.
PUT is for updating existing resources. A PUT call should be idempotent, i.e. issuing the same request twice will end in no side effects.
To get an overall clue on how RESTful services work, read this article.
And yes, if you want your users to submit a complex set of parameters JSON/XML is the best way to go of course.