Single API endpoint pros and cons - api

I am creating API and trying to figure out is planned approach any good.
That API is not public and it will be used by SPA and mobile app that I build.So I am thinking of GraphQL-like design but without posting json and with regular HTTP methods.
Something like this for GET methods:
Example 1 - get users with specific fields(_join indicates sql table join), ordering and limit:api.com?table=users&displayFields=id,name,email,address,tel,country_join&orderBy=asc&orderColumn=name&offset=0&limit=10
Example 2 - get users based on search parameters with all fields, ordering and limit:api.com?table=users&search=John&searchFields=name,email&orderBy=asc&orderColumn=name&offset=0&limit=10
I assume this is bad since REST is standard, otherwise I would see much more examples of this approach.
But why is this bad? For me it seems easier to develop and more flexible to use.
Is proper REST API for examples I provided easier to implement, safer, easier to use or cache?

The main difference I see between putting the variables in the url vs the request body are:
the length of the data as the url length is limited while the request body is not
special characters to be escaped in the url which can lead to long and unclear url
These are 2 pros in favor of data in request body, but I agree that data in url is much simpler to test and use as tou don't need an http client tool like curl or postman to validate your endpoints.
REST however has stricter conventions if you want to fully implement it:
use the right http requests (get, post, patch, delete and put) to implement crud operations on one single endpoint
return the right http code as a result
use standard data format for input and output (json or XML)
For better interoperability between systems it's advised to comply with REST and microservices design patterns.
For small applications we can follow some shortcuts and not comply fully. I have integrated several services so far and each time I can tell you no one of them implements standard REST :-)

Related

Best practice for pagination in API REST

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.

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.

Structuring online documentation for a REST API

I'm building my first Rest API which serialize data to JSON and XML formats.
I would like to provide an index page to API clients, where they would be able to choose implemented endpoints.
What information do I need to include to make my API most useful, and how should I organize it?
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
https://api.coinsecure.in/v1
https://api.coinsecure.in/v1/originalUI
https://api.coinsecure.in/v1/slateUI#!/Blockchain_Tools/v1_bitcoin_search_txid
At the very top level I think quality REST API docs require at least the following:
a list of all your API endpoints (base/relative URLs)
corresponding HTTP GET/POST/... method type for each endpoint
request/response MIME-type (how to encode params and parse replies)
a sample request/response, including HTTP headers
type and format specified for all params, including those in the URL, body and headers
a brief text description and important notes
a short code snippet showing the use of the endpoint in popular web programming languages
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

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