Structuring online documentation for a REST API - indexing

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.

Related

How to implement api versioning?

I have an web API application that will serve many clients at different times of release and now i need to implement a versioning. Because the API code will be constantly updated and API users will not be able to instantly change their API. Well, the standard situation is when you need to introduce versioning in general. I'm finding a way to organize it inside my API. It's clear that it will not be different folders with an application on the server, conditionally called app_v1, app_v2, app_v2.1, etc., cause this is duplication, redundancy and bad practise.
It's look like will be one application, and in the controllers at the code level there will be a division of the logic already, like If(client_version==1) do function1() else if(client_version==2) do function2(), etc. It seems that git supports tags, this is something similar to versioning, but because all supported versions of the application need be on the server at the same time, this is not about that. how i can realize an architecture in this case?
There are many well-known ways to use API versioning to make code work with older versions. (backward compatibility). The general purpose of API versioning is a way to make sure that different clients can use different versions of an API at the same time. I've seen several ways to do API versioning, such as:
URL Path Versioning: In this method, the number of the version is part of the API endpoint's URL path. For instance:
https://api.example.com/v1/assets
https://api.example.com/v2/assets
URL Query String Parameter: In this method, the version number is added to the API endpoint's URL as a query string parameter. For instance:
https://api.example.com/assets?version=1
https://api.example.com/assets?version=2
HTTP Header: In this method, the version number is put in an HTTP header, like the Accept-Version header. For instance:
Accept-Version: 1
Accept-Version: 2
If you are using dotnet for you project I would like recommend to standard library for that recommend to check this out. Or you can find solid materials in term of WebApi Versioning following link by #Steve Smith.
There is another answer.

URIs in REST API endpoints according to Restful practices

I am planning to have these endpoints for our REST APIs.
PUT /tenant/:tenantId/users/save/:username
POST /tenant/:tenantId/users/invite
GET /tenant/:tenantId/users/fetch
GET /tenant/:tenantId/users/fetch/:username
PATCH /tenant/:tenantId/users/activate/:username
POST /tenant/:tenantId/groups/save/
Verbs such as save/fetch/activate are from the consistency point of view. Are these RESTFul according to the REST principles? How should these be changed if at all? Any recommendations?
According to this REST Resource Naming Guide:
RESTful URI should refer to a resource that is a thing (noun) instead of referring to an action (verb) because nouns have properties which verbs do not have – similar to resources have attributes.
And also
URIs should not be used to indicate that a CRUD function is performed. URIs should be used to uniquely identify resources and not any action upon them. HTTP request methods should be used to indicate which CRUD function is performed.
So let's take your first URI as example
PUT /tenant/:tenantId/users/save/:username
Here you are using the verb save. As mentioned before you should not be indicating a CRUD operation in the URI, in this case using a POST would be more appropriate.Here is a guide with the purpose of each HTTP verb. Knowing this, I think that for example a more appropriate URI for that case would be something like
POST /tenants/:tenantId/users/:username
In this cases:
GET /tenant/:tenantId/users/fetch
GET /tenant/:tenantId/users/fetch/:username
you should remove the fetch because you are already telling through the GET verb that data is being fetched. Same goes for the 6th example.
But, this doesn't mean that you can't use verbs in your URIs, in fact there is a specific category called controller which as mentioned in the same guide:
A controller resource models a procedural concept. Controller resources are like executable functions, with parameters and return values; inputs and outputs.
Use “verb” to denote controller archetype.
This controllers resources could go well (I asume) with for example your
GET /tenant/:tenantId/users/activate/:username.
But I would think that the verb activate should go last:
GET /tenant/:tenantId/users/:username/activate
First note: REST doesn't care what spelling conventions you use for your resource identifiers. Once you figure out the right resources, you can choose any identifiers for them that you like (so long as those identifiers are consistent with the production rules defined in RFC 3986).
"Any information that can be named can be a resource" (Fielding, 2000), but its probably most useful to think about resources as abstractions of documents. We use HTTP as an application protocol whose application domain is the transfer of documents over a network.
GET
This is the method we use to retrieve a document
PATCH
PUT
POST
These methods all indicate requests to edit a document (specifically, to edit the request target).
PUT and PATCH are each ask the server to make its copy of a document look like the client's local copy. Imagine loading a web page into an editor, making changes, and then "saving" those changes back to the server.
POST is less specific; "here's a document that we created by filling in a web form, edit yourself appropriately". It is okay to use POST: after all, the web was catastrophically successful and we're still using POST in our form submissions.
The useful work is a side effect of these edits.
Are these RESTFul according to the REST principles?
Do they work like a web site? If they work like a web site: meaning you follow links, and send information to the server by submitting forms, or editing the webpages and submitting your changes to the server, then it is REST.
A trick though: it is normal in REST that a single method + request uri might have different useful side effects. We can have several different HTML forms that all share the same Form.action. Uploading changes to an order document might have very different effects if the edits are to the shipping address vs to the billing information or the order items.
Normal doesn't mean obligatory - if you prefer a resource model where each form request goes to a specific resource, that can be OK too. You get simpler semantics, but you support more resources, which can make caching trickier.

Single API endpoint pros and cons

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 :-)

Guide to designing complex API that works in a RESTful way?

I have tried out the RESTful API concept and found out that its a great mindset for building resources APIs. For example, adding comment to post would be
POST /posts/{id}/comments
However, there are some cases, correct me if I am wrong, that the expected APIs can not really be model as a simple CRUD
For example, adding product to the system requires adding picture, adding multiple tags specify its category?
How do I do this the restful way?
1.) Do I force the API user to follow after multiple API calls?
POST /pictures -- add picture
GET /categories -- get selected category
POST /tags -- add tags
POST /products -- input picture, category, tags ids as JSON fields
2.) Do I use nested object which automatically do find all subresources?
POST /products -- input nested JSON array with picture/category/tags object field
In this case, all subresources will be existing resources instead of some (picture, tags) that should be posted.
Also, what would happen if adding picture succeed internally but adding tags failed?
3.) Do I just do a casual API? How does this fit with REST? Doesn't this break the RESTful idea?
POST /add_products
Is there any guide to deal with complex API for RESTful APIs?
Thank you.
In my opinion, one of the biggest misconception people have about REST is that internal models (tables in db or document in mongo) and REST resources must be same. REST resources can be a real model or it can be an abstract entity as well which might not exist in db.
So in this case, your url with POST i.e. POST /products request is perfectly alright as far as REST is concerned. And advice from my personal experience - One doesn't needs to be too dogmatic about url as long as basic principles of REST are conserved such as
Use right HTTP verbs
Use right status codes
Cacheable architecture
Unique indentification of resource by url
Hypermedia (if you can go that far)

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