REST API URL naming convention - api

I would like to check if an order is active with retrieving the order details. I have an enpoint designed similar to what is listed below
/order/{order-id}
However I was to check if the order is active without retreiving the details of the order. Which of the below is a better approach to do this or are there any other alernatives?
/order/{order-id}/is-active
or
/order/is-active/{order-id}

Django Rest Framework, a widely used REST API framework, uses the second form /order/{order-id}/is-active.
See Routing for extra actions and Reversing action URLs for examples of this in their documentation.

Related

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.

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)

How can I handle the resource expansion while designing/making the transitions in Moqui?

I am not able to figure out how should I handle the names of transitions so that it is aligned to the best practices of RESTful API in case of resource expansion.
For instance, if I want to fetch all the orders for a particular customer the URI should be like https://api.website.com/customers/1000/orders.
I am able to make the transitions restful for a single resource i.e. customers or orders (as it was demonstrated in the Example App file in Moqui.) but was unable to find any example which will solve the purpose of resource expansion.
The problem that I am facing is while designing the transitions as per the best practices of a restful API. The ExampleApp.xml only has examples for a single resource i.e. Example Entity.
If I take the case of the data model used in HiveMind regarding Project management then the URI should be like this according to the best practices
For fetching all Projects- https://api.website.com/projects
For fetching a Milestone for a particular Project - https://api.website.com/projects/DP/milestones/DP-MS-01 (Here, DP is the Project Id)
For fetching a Tasks of a particular Project- https://api.website.com/projects/DP/tasks/DP-1
Now if I am designing an API in Moqui framework, this is how I have to name the URIs
For fetching all Projects- https://api.website.com/projects
For fetching a Milestone of a Project- https://api.website.com/projects/DP/DP-MS-1
For fetching a Task of a Project- https://api.website.com/projects/DP/DP-1
So you can see that these URIs are confusing as I am not able to differentiate between the URI for fetching a milestone or a task.
I can still make the URIs as per the best practices of restful API design by checking the path-parameters (i.e. if tasks is in the path parameter then execute the task related operations and similarly for milestones). But this approach will not be a clean one as its maintenance will become difficult if the parameters in the URIs are too many like https://api.website.com/projects/DP/milestones/DP-MS-1/tasks/DP-1/worklogs/DP-1-WL-2/party.
This is just an example scenario in which I want to get the party/person who has added worklog for a task in a particular milestone of a particular project. This is the case of one data model i.e the WorkEffort.
But what about party, customers, orders, products etc. data-models? Designing an API will become an extremely tedious job for the developer of the API.
So I was just asking if there was another cleaner approach that is implemented in Moqui which I could use as reference?
In the latest version of Moqui Framework (not yet released, just available in the GitHub repo though will be part of the next release) there is now an automatic entity REST interface to do find and CrUD operations.
It supports patterns like that described in this question and many others, for some examples see the comments in the rest.xml screen file (that handles the entity REST requests):
https://github.com/moqui/moqui/blob/master/runtime/base-component/webroot/screen/webroot/rest.xml
The concept in Moqui that handles this is path parameters. The easiest examples of it are in the RESTful service examples in the ExampleApp.xml screen:
https://github.com/moqui/moqui/blob/master/runtime/base-component/example/screen/ExampleApp.xml
The example request, in a comment in that screen, with curl looks like:
curl -X GET -H "Authorization: Basic am9obi5kb2U6bW9xdWk="
http://localhost:8080/apps/example/ExampleEntity/TEST2
The transition that handles this request looks like:
<transition name="ExampleEntity" method="get" read-only="true">
<path-parameter name="exampleId"/>
<actions>
<entity-find-one entity-name="Example" value-field="example"/>
<script>ec.web.sendJsonResponse(example)</script>
</actions>
<default-response type="none"/>
</transition>
Note the use of the transition.path-parameter element, and that this transition only applies to requests with the HTTP GET method. Everything after the transition location in the URL is treated as a path parameter and put in context fields, like "exampleId" above, in the order of the path-parameter elements.
In your case you would have 2 path parameters, a customer ID and the "orders" string telling it to retrieve orders for the customer.

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.