What would be a RESTful URI for retrieving all Products created by a particular Client? (you have the client's ID) - rest

So the application is for a warehouse and you need to retrieve all of the products in the warehouse created by a particular client. What would a URI that is RESTful look like to accomodate this?
Here are some ideas that I had:
/Product/Client/[the client's ID]
/Product?clientID=[the client's ID]
What would a RESTful URI for this scenario look like?

From my point of understanding, first one is better options. In first scenario, you will only check the route from the URI and client id will be in the body param. In the second scenario, you are adding clientsID in the header. Although I am not a master but what saw the way people write, they follow the first option. You might get an idea from here: http://www.restapitutorial.com/lessons/restfulresourcenaming.html
Wait for the response from master in that area. thanks

You're identifying a specific client, so start with
/Client/[Client ID]
and then specify a resource "belonging to" that client
/Client/[Client ID]/Products

It all depends on the use case for this requirement.
If the client would usually navigate to a client, and then needs to view its products, then as #esorf said:
/client/{clientId}/products
However, if the client is displaying products for various clients (albeit only one at a time), something like this might make more sense:
/products?clientId={clientId}
This latter one could also be extended to use URI Templates in order display products of more than one client like so:
/products{?clientId*}
which expands into
/products?clientId={clientId1}&clientId={clientId2}

Related

Rest API Hateoas : Should API response have identifiers as hard coded or as placeholders?

Link to the HATEOAS This is the link to the Hateoas article (snapshot below) where the identifiers of the resource is part of the URL i.e. 12345. Here the API response has the final API relative URL i.e. /accounts/12345/deposit and the client just needs to hit it.
Link to the Github Users API This is the link to the Github API (snapshot below) where there are lots of placeholders for identifiers. How will clients modify these URLSs and add a value in these placeholders? For example, {/gist_id}, {/other_user}.
Isn't passing the URL with id value instead of placeholder better? Why and when to rely on different clients to add values in these placeholders?
Hypertext as the engine of application state (HATEOAS) is a bit more than just the usage of links. In essence it enforces the interaction model that is used on the Web for two decades quite successfully. On the web a server usually "teaches" clients (browsers) to achieve something via the help of link relations, that can be used to automatically download related resources or give a hint on the reference resource, and Web forms, that define the syntax and semantics of each of the respective supported (input) elements, i.e. a text field, an option element to select one or multiple choices, a drop down or even a slider widget. Based on the affordance of each of the elements a client knows i.e. that a button wants to be clicked or pressed while a text fields wants some user input and stuff or a link annotated with the prefetch link relation name may be downloaded automatically once the current page finished loading as a client might invoke it next or a preload link relation might instruct a user agent to load the referenced resource early in the current page loading process.
The form not only teaches a client about the supported fields a resource has but also about the target URI to send the request to, the HTTP method to use wile sending the request as well as the media-type, which in the case of Web forms is usually implicitly set to application/x-www-form-urlencoded.
In an ideal world a client just uses the information given by the server. Unfortunately, the world isn't perfect and over time people have come up with plenty of other solutions. Among one of them is URI templating that basically allows clients to use a basic URI and fill out certain placeholders with concrete values. As making use of templating requires some knowledge of the URIs intention or the parameters you need to pass, such capabilities make only sense as part of media-type support.
Plain JSON (application/json) has by default no support for URIs whatsoever and as such a user agent receiving a plain JSON payload might not be able to automatically replace a template URI with a concrete one out of the box. JSON Hyper-Schema (application/schema+json) attempts to add link and URI template support to plain JSON payloads. A user client though needs to be hinted with the appropriate media-type in order to automatically resolve the full URI. As such, the user agent also has to support that respective media type otherwise it won't be able to process the document (resolve the template URI to a real URI) successfully.
JSON Hypertext Application Language a.k.a HAL JSON also supports URI templates for links. application/collection+json does support two kinds of templates - query templates and objects-template. The primer one is similar to a URI template by allowing to append certain query parameters to the target URI upon sending the request while the latter one allows to define a whole object that contains all the input elements used to add or edit an item within the collection. JSON-LD does not really support URI templating AFAIK though it uses the concept of a so called context where certain terms can be used to abbreviate URIs. As such something like name can be used within the context for a URI like http://schema.org/name.
As you can hopefully see, the support for URI templating depends on the media-type used for exchanging data. In the case of the outlined github example GET /users/:username this more or less resembles a typical Web API documentation, similar as it is done in a Swagger API documentation, that unfortunately has hardly anything to do with HATEOAS.
For your top example (banking), you should absolutely include the complete URL, with account numbers (IDs), so that the client does not need to translate/substitute anything. This is the most common scenario with HATEOAS. However, GitHub does have those "placeholders" for endpoints that could contain multiple values. You can't include the "following_url" for every user in the response, it's not practical. So you have to determine the "other_user" value another way and make the substitution. Personally, I haven't even had this use case with any of my applications and all of my HATEOAS URLs resemble you first example (though I prefer full URLs not relative). Unless you have specific cases like GitHub does, it's not necessary to use any of these placeholders. Even GitHub only uses that where they could be multiple values. For fixed value URLs, they have the username (like your account number) in the URL ("octocat").
According to me we should not give the direct url in the body
We should always parameterized the api and get details form there.
In simple case if Id of data change than every time data need to update for detail url.
Else if it’s dynamic you will never face this issue.
And this also come under best practices.

What should be the Rest URL for the action "Move the competitor from team1 to to team2"

I am looking for a good URL, following REST principes, to "Move the competitor from team1 to to team2
My first guess is :
/teams/{oldTeamId}/{newTeamId}/competitors/{competitorId}/move
But it doesn't look much like REST.
Should I break it into 2 basics calls ?
Remove competitor from team1,
Add competitor to team2,
Should I remove some data from URL and pass it into the body ?
I don't really know what to do for this one.
Think about how you would implement this API as a web site.
You would probably have a link to a form -- it might be a form where the competitor, old team, and new team are all blank, or it might be a form where the competitor and old team are pre-populated. Your consumer updates the default information in the form as required, and submits it.
Notice the first point (raised by Roman Vottner as well) -- your consumer doesn't need to look at the URL at all. The client knows the HTML form processing rules, so it can create the correct HTTP request without knowing anything about the domain.
The second point is that, since the client is just submitting the form to wherever the HTML tells it to, you can make that anything you want.
One of the interesting properties of HTTP is cache invalidation. See RFC 7234, any non error response to an unsafe request will invalidate all cached representations of one resource.
So you can choose which resource gets invalidated by specifying its URI as the target of the form. In effect, it gives you a mechanism for ensuring that a consumer can read its own writes.
So some reasonable choices for the target might be
/teams/{oldTeamId}
if the team roster is the most important thing. Or
/competitors/{competitorId}
if the resource that describes the player is what is most important.
I don't really know what to do for this one.
Concentrate on make it easy to use. Your resource model is not your domain model is not your data model.
It will likely be useful to watch Jim Webber's talk REST: DDD In the Large to get clearer insights into what your "REST" API should really look like.
To answer your questions, I would not break it into two calls, I would however take some data from that (GET) url and put it in the body of your request. The request would probably be a POST or PUT (or maybe even patch), but definitely not a GET since something is actually changing.
As for a solution, how about a POST request to a /transfer. After all you are (could be) creating a new transfer which takes for example the player, their new team and maybe their old team.
I would use URL to identify the resource which in this case seems to be a competitor's team.
So would
Make the url as /competitors/{competitorId}/teams
Make the call PUT
Have a body with newTeamId and if required the oldTeamId.

REST API Design for special actions on resources

I need to design an operation “duplicate” for "articles".
My thought was: a POST on apibaseurl/articles/{id}/duplicates and returning a 200 OK with the URI of the created duplicate, which's URI however will conform to the template apibaseurl/articles/{id}.
When issuing a GET to apibaseurl/articles/{id}/duplicates however, there will not necessarily be a list of duplicates (meaning: the server will not keep track of all duplicates created for an article - the "duplicate" relationship is ignored by the server outside the scope of the request)
Questions:
is my suggested solution OK?
does it not violate any RESTful principle by having the URI of the created object point to a location not under the resource under which it was posted?
would I have to provide a client with the possibility to list all duplicates for an article?
is my suggested solution OK?
It looks fine to me.
does it not violate any RESTful principle by having the URI of the created object point to a location not under the resource under which it was posted?
No, that is not necessary. You POST to a collection resource but this does not force you to return a Location header pointing inside this collection.
would I have to provide a client with the possibility to list all duplicates for an article?
If you have a use case for this, you could provide it. But if there is no business interest in listing the articles created as duplicates of an existing article, you don't have to.
Go ahead :)

REST API + hacks/REST + RPC hybrid. Do I get it right?

TL;DR How to mix REST requests with some non-REST requests in SPA(frontend/backend)? Or might be I just get REST wrong?
We are planning new API for SPA and mobiles(plus probably some 3rd parties). There will be some requests which, I suppose, can't be covered by REST.
I am speaking mostly about requests which would make backend do something, which would modify state of document or give some additional info, based on document, but request itself is rather simplistic.
Here is really easy example. I want to add a comment to blog post. For example I might do it like this:
Create comment. POST /comment
Create connection between author and comment. POST /comment_author or PUT /comment with author_id.
Create connection between comment and post. POST /comment_post or PUT /comment with post_id.
I also could do something like POST /comment with {author_id, post_id} which actually seems most logical here.
Everything did work, comment added to blogpost and associated with author.
Now customer wants to get statistics for his comment, like words stats and letters stats. As a part of request I pass comment_id. Backend might update comment with stats data, it might create separate entity and link it with comment or it might just send me those stats for this comment without saving.
So what would be the choices?
I can do something like:
GET/PUT /comment/:id/stats. For me it seems already hack, because as a result I don't want a document of type comment, but document of different type. As well as I don't send stats with request, I calculate them on backend so using PUT seems wrong.
POST/GET /comment_stats/:comment_id. Seems legit, but if I don't have a document/entity of type comment_stats, that would mean that I actually ask backend to create something, backend would reply me OK/Created, but actually I don't have this document somewhere saved.
So, while I understand REST != CRUD, I thought to use REST for simple CRUD and, for cases like that, to use RPC. So in RPC scenario I would just call POST comment.stats(comment_id)
My questions are what would be better choice in this situation, as well as are my thoughts about rest/rpc right?
I would go with GET /comment_stats/:comment_id for proper separation of concerns, so that report code doesn't clutter the comment resource.
It doesn't matter if you don't actually have a comment_stats document, or how the data is represented on your backend. The REST API is just an abstraction over your backend.
In general, for any non-CRUD action like this, it's better anyway to create a new resource and deal with it as if it was a "machine": you send some instructions to the machine (via a GET or POST call). The machine executes it and then returns the result. A simple example would be an endpoint to convert images: you create an /image_converter end point (the machine), you POST an image to it, it converts it, and sends back the image. /image_converter would have no associated entity/document in the database but for the end user it's still a resource with a logical behavior.

Yet more questions on RESTful URIs

Numerical IDs vs names
As an example, which of these would you choose for identifying a single transaction, from a single bank account, for a single company:
/companies/freds-painting-ltd/accounts/savings/transactions/4831
/companies/freds-painting-ltd/accounts/1/transactions/4831
/companies/62362/accounts/1/transactions/4831
You idiot, something totally different! Crikey, did you even READ Fielding's dissertation?
Now, I think the 1st one is the most readable. If I have more than one company, or if I'm someone like an accountant managing multiple companies, it's immediately clear which company, and which account, I'm looking at. It's also more bookmarkable/emailable and would prevent 'fishing' for other companies by changing the company ID. I would want transaction IDs to be unique to an account (I.e. Both 'savings' and 'current' accounts could have transaction '1'
A 'company' will be my 'top-level', or 'first class' resource. Nothing at all would ever be shared between companies. As such, it would be the ideal candidate for a shard (or 'ancestor'/'namespace' in Google App Engine parlance). So I'd only have to worry about the account names being unique within one company. Every company could have an account called 'savings'.
Not sure what the situation in the rest of the world is, though LTDs or PLCs in UK would have a unique name, there could be many 'Dave's Window Cleaning' businesses (what's know as a trading name).
The business owner(s) could potentially opt for the top level /company/company-name URI to be public, and contain some basic details like their website, contact details etc, but everything below that would NEVER be accessible by search engines.
So my thoughts/concerns are:
1) Is it reasonable, when someone signs in to add their business, to say "Sorry, 'Dave's Window Cleaning' business is taken. How about 'Dave's Window Cleaning Portsmouth' (Having taken their location in another field)? My worry with this is that, for a more well known company, you're giving away the fact that they have an account with you. Or that someone could use that form to search for names. Perhaps not a biggie.
2) The size of the company name. Would it be reasonable for a name like 'Dave's Window cleaning, gardening, and loads of other stuff'? Thus creating a URL like 'daves-window-cleaning-gardening-and-loads-of-other-stuff/'
3) How to deal with someone changing their business name - I would approach it by creating a new company with that string ID, copying over everything, then deleting the old resource. The original URI would return 404 rather than redirecting - as you can't guarantee someone else won't want to take the now unused name, or even if more than one person has used the same name in the past.
4) Should the 'real' unique ID be an number in the back end, and for every request to be handled by first doing a query for what company ID this name actually related to.
5) The impact of searching for a transaction in the persistence layer.
6) The possibility of URL rewriting, but then that wouldn't work cleanly in GAE, nor would it solve the issue of ensuring company names are unique.
RESTful webservice vs RESTful website
So, we potentially have this lovely RESTful webservice that the latest snazzy iphone/android app can use (delusions of grandeur). But what about the main website itself? I note, right now, that the URL I see at the top of my page is not 'RESTful': /questions/ask is an action. There is no 'ask' resource on the server. It's more the state of the page, the preparation for POSTing to /questions/ - or if I'm editing, PUTing to /questions/{id}
I also note that Stackoverflow has URIs like /questions/362352/name-of-the-question, and that the latter part can be omitted, and one will be redirected to it.
Should I host a completely separate webapp that consumes my lovely webservice (from the same domain)? Do I even need a separate REST server, or can I rely on content negotiation (JSON/XML) and HTTP verb to select the right method (I'm using Jersey), and return the right representation?
So I could have /companies/aboxo/ return the whole HTML page (using stringtemplate.org) if it's a GET /,text/plain or test/html, and JSON/XML for others?
But what happens for 'add/edit/delete' transaction? Would GET / /companies/freds-painting-ltd/savings/transactions/?template=add be ok (or GET ../transactions/352?template=edit), and that would return the right HTML?
Thinking about this last detail is driving me mad for some reason.
Comments, suggestions, outright ridicule - all welcome!
Marcos
Rails solves the "id vs name" problem by displaying both in the URL but using only the id to actually identify eg:
/companies/62362-freds-painting-ltd/accounts/1-savings/transactions/4831
ie - for the ones that have a "pretty url" the function that generates your path write both the id and the name... but for your router, where relevant: you strip off everything thats not the id.
incidentally, it means your customer could actually write whatever they like into the URL and it'd make no difference:
/companies/62362-i_luv_blue_turtles/accounts/1-your_mum/transactions/4831
and your router still just sees:
/companies/62362/accounts/1/transactions/4831
:)
For a cannonical URI I suggest just /transactions/{id} as I presume the transaction knows what the company and account is. Therefore, #4 :-)
Is SEO a concern? I presume you don't want random folks off the internet googling for X company's transactions?! Therefore, I would just keep names (which may change) out of the URI.