Best practice for pagination in API REST - api

I'm new in API developement and I wanted to know what is the best choice to create pagination :
GET resquest with query params (sort, limit, etc)
POST request with params in the body (sort, limit, etc)
I was more on the GET but my coworkers thinks POST is a better choice, so I just wanted your opinion.

GET would be the usual choice.
General purpose components will understand that the semantics of GET are safe, which means they are also idempotent. If a GET request receives no response, you can automatically retry it without any concerns about loss of property.
Furthermore, if all of the information you need to identify the resource is included in the URI, then you can bookmark the URI, or paste it into an email, or link to it in a document, and it will all "just work".
Also, using GET -- with all of the relevant details encoded into the resource identifier -- means that the response can be cached and re-used. The constraints on caching POST requests mean that you can't capture the information in the request body.
At some point in the future, HTTPWG will register a new HTTP method to cover the safe method with a body case, which may change some of the answers.
In the meantime, it is okay to use GET.

GET is the recommended way to do this, because the answer can be cached and the goal is reading not writing. You can use the query string or range headers for pagination. The exact solution depends on your needs. There are a few standard query languages for this, like OData, but they are overkill for a simple API. Building a custom solution on top of URI templates might be a better choice, or there are non-standard query languages too like RQL, which can be completely or partially implemented in your solution.

Related

Rest API resources: composed for post but separate to get is ok?

I'm creating a set of RESTful API and I have this question: I have a resource that has some images attached and I'm creating my resources like this:
POST to /resource: create the object and save the images to the server.
GET to /resource returns the object but no the images, GET to /images returns the images.
My question is: is this compliant with REST or should I either make the resources completely separate or completely unified?
I choose this solution because when posting I for sure send the images, but I may need them or not when doing a get.
is this compliant with REST
It's fine - for instance, if you look at the way that Atom Publishing works, you'll see that when you post a media to a collection, two resources are created (the Media Resource and the Media Link Entry).
However, fine here means you are making tradeoffs. In particular, cache invalidation is more challenging when you a POST to one resource may change the representation of a different resource.
HTTP caching semantics are optimized for the common case, which is that a given request changes only the target resource; no spooky action at a distance.
That doesn't mean that this is the Right Way, but rather that you should understand that this is the way that HTTP makes easy, and in other cases you need to pay attention to the details.
POST can basically mean anything, and unlike PUT and GET (for which there is a bit more of a direct relation), POST is allowed to result in all kinds of side-effects, including the creation of 0 or more resources.
POST is basically the 'anything goes' method.

Is it ok for a REST api to be exposed via two HTTP methods?

The problem is that we have a complex query string for a search api and want to let the users have convenience of using body instead. So we want to allow both GET and POST(or PUT).
I understand that there will be a debate of search being a read only operation and it should be GET only as per REST standards. Also PUT is not cache friendly as i understand.
But i also know that its ok to deviate at times from the REST standards. But does it make sense to have two methods for client's convenience?
Using POST directly to query data is not a good thing, precisely for the reasons that you mentioned. If your search string is complex, perhaps you could simplify things by splitting the querying process in two steps - one involving a POST, and another one involving straight GETs.
The first step creates a query template using the POST. The query string is sent via message body, and becomes a new resource that users can query through GET. Query string allows for parameters, in a way similar to SQL queries. Taking a wild guess at how your query might look, here is an example:
(userName = $name) || (createdBefore > $asOf && deleted=false)
Your users would POST this in a message body, and get a new resource identifier back. This resource identifies a parameterized "view" into your data. Let's say the resource id for this view is aabb02kjh. Now your users can query it like this:
https://app.yourserver.net/aabb02kjh?name=airboss&asof=20140101
This adds some complexity to your API, but it lets users define and reuse query templates with very simple and standard query strings.
Interesting question. I mean by POST -> PUT,DELETE there are common workarounds for overriding HTTP methods:
sending a _method hidden input field with the post data
sending a _method query param in the URL
sending an X-HTTP-Method-Override header with the post
etc... So if they are valid (I am not sure about that), then you could use the same approach by GET as well.
According to REST constraints: cache and the uniform interface, and the HTTP method definitions, you have to use GET by retrieval requests. There are only a few URL query languages to make URLs readable, for example RQL, but you can always pick your favorite query language and serialize it for URL usage...
Another interesting approach to add link descriptions about the URL. (But that is very new for me either.)

RESTful API GET method parameters

We are creating a RESTful API (PHP on apache server) which will communicate with an Android application. Im new for this so excuse me if my question is dumb.
I want to ask for data from the api so I need to use GET method in the request taking into account the semantics. I have to send some additional data to specify what data am I requesting. In GET requests, I cannot send form data fields so how should I attach the data?
Using POST (but this is not semantic)
request header: POST http://example.com/api/v1/serials
request data: date_from=2013.01.01&date_to=2014.01.01&userid=112&is_in=0&starts_with=afx00
using GET and adding url params (I don't know if is this a good practice in a REST API)
request header: GET http://example.com/api/v1/serials?date_from=2013.01.01&date_to=2014.01.01&userid=112&is_in=0&starts_with=afx00
or making well formed URIs with no url params in GET (not sure about this as well.)
request header: GET http://example.com/api/v1/serials/date_from/2013.01.01/date_to/2014.01.01/userid/112/is_in/0/starts_with/afx00
Which one fits the best in the RESTful API architecture? Which should I use and why? Or maybe are there any other options for what I want?
Without question using URL parameters is best. It allows consumers to query for serials using their choice of filters. Your API should support returning results based on UserId alone, or a date range, or both. Or other combinations of inputs that make sense.
Embedding the key/value pairs of the filter in the resource path is an anti-pattern. It's difficult to understand what each path element means, and you would need to contort your routing engine to accommodate additional filter criteria. It also provides no flexibility in terms of choosing what filter criteria to use - you would in fact need to construct multiple resources paths for each combination of filters. And there is the management of ordering each pair (with URL params, ordering doesn't matter). Probably more reasons to avoid this, but those are the first that spring to mind.
Bot GET methods can be used. It is your choise. But I'll prefer using url params. It is easier.

Implementing complex search in RESTfull service

We are trying to implement a complex search functionality in Rest service using coldfusion 10.
Something like projectid=1 and active=1 and (ManagerName contains John or ManagerName contains alfred)
One way of doing this is ?projectid=1&active=1&ManagerName=[John,Alfred]. However this does not serve my purpose as the ManagerName search will not return the required result. Also, as the number of search filter grows, the query string becomes tough to handle.
I tried to get an xml (with all search filter) as an input through HTTP Get Request, but that did not help, as GetHTTPRequestData() does not reflect the xml content.
Is there any means to pass an xml/json through an HTTP Get Request??
Will it be a bad practice, if xml is passed by a HTTP Post Request??
Are there any other options to pass complex filter param to a REST service??
i have gone through a lot of post on the site for similar question, but still could not find a solution to my problem.
GET should be idempotent it should not modify the state of the Resource. strictly limit get usage to Read operations
your POST triggers Resource Creation i.e along with payload (xml/json).It is very bad practice to use POST for search.
Also you should take-care of the Cache-Control as your GET requests might get cached and if your search is real time you might get stale data.
You can take example as stackoverflow itself
https://stackoverflow.com/questions/tagged/rest?sort=newest&pagesize=30
In above URl, path elements questions , tagged, rest derive subset of question resources.
The query parameters suggest filtering of those which met the creiteria.

Do REST API URLs have to look like this?

Is it true that to implement a RESTful API, one has to implement a URL structure that looks like this
http://example.com/post/
http://example.com/post/123
where the /123 would be used for edit, delete
Another way to ask the question is: can a URL that looks like this be called RESTful?
http://example.com/script.php?method=get_title&blogid=123
You don't have to design your URI structure like that. It could also be /some_obscure_string/base64_encoded_title/unique_id. This could also be RESTful, depending on several other factors.
But there are several best practices on how to design URIs in a RESTful web application and being as simple and as human readable as possible is one of them.
Your example http://example.com/script.php?method=get_title&blogid=123 could also be RESTful, but the query parameters indicate that some kind of RPC- or RMI-over-HTTP is used instead.
To sum it up: Don't put too much thought into your URI design. This will come automatically with a good and proper RESTful design of your application.
The Idea behind REST is that every resource has it’s own URL and you use the different HTTP methods to interact with those resources. It makes sense to define the URL structure so that the hierarchy between different resources is reflected in the URL, but you don’t have to.
If you have URLs like this
/all-posts/
/first-post
/some-stuff/second-post
/third-post
you still could provide an RESTful API to this. The Idea is that a GET to /all-posts/ returns a list of the URLs of every post object and the client uses those URLs to interact with the resources. Basically the URLs should be treated as opaque data by the client.
As long as the URL that is embedded in the client doesn’t change you also could change the structure without having to change the client.
Your example URL probably doesn’t belong to a RESTful API, since it contains a method get_title. In REST a URL represents a thing. What is to be done with the thing (should it be modified, should it contents be retrieved, ...) is not part of the URL, for that REST uses the different HTTP methods.
A key aspect of REST is that the url is the resource. a uri like
http://example.com/script.php?etc-etc-etc
doesn't put the resource identifier in the resource portion of the uri. that's not to say that a RESTful API shouldn't ever use get parameters; in fact, that's just fine:
http://example.com/posts?sort=date_asc&offset=20&limit=10
might be a great way to get the URI's of the 3rd page of oldest posts. However, using get parameters in this way should only be used in requests where the method is also GET. PUT and especially POST methods should really use simple uri's with the resource that will be affected in only the path portion.
RESTful URI design is all about resources access and they should be structured in the RESTful manner, so you should not have any query strings.
e.g. of GET
authors/
authors/1
authors/1/books
authors/1/books/10
authors/1/books/10/summary
etc.
Anything and everything is called RESTfull these days, just look at some of the responses by it's inventor Dr Roy Fielding and you'll get some ideas. It is worth doing some reading on the subject.
P.S you do not need post,get etc in your URIs, HTTP protocol is at present mostly used for consuming REST APIs and you can pass verb as a part of the call. Also there is a concept of content negotiation i.e you can request any available format from REST API (json,xml atc).
The REST concept is really based on the fact that it is URL driven, and not driven by large data-blobs. With REST, you don't have to pass a giant soap request to invoke a method - your method call/object creation/whatever you want to do is invoked simply by the URL, and the verb you used vs that URL.
Example URLs:
GET http://del.icio.us/api/
GET http://del.icio.us/api/peej/tags/
GET http://del.icio.us/api/peej/tags/test
DELETE http://del.icio.us/api/peej/bookmarks/[hash]
The structure of your URLs doesn't matter. What does matter is that each URL identifies exactly 1 resource. Each resource can have multiple URLs that point to it but each URL should only point to 1 resource.
This can be helpful. Ref:
RESTful service URLs