Rest convention: Should api send details api url for listings or clients hard code them? - rest

We have listing and details page for mobile, desktop, android and ios?
We have two apis- one for listing and other for details of those listings. So one api is assosiated with other.
listing api looks like:
/api/books/?price=100-300
details api looks like:
/api/book/{bookId}
listing api in response sends back details api link for each listing:
For example:
Request:
/api/books/?price=100-300
will have Response:
{
"books":[
{
"id": 1,
"price": 120,
"pages": 400,
"detailsUrl": "/api/book/{bookId}"
}
]
}
The problem is, should I send detailsUrl with each listing or let all the clients create this? Since they have bookId, they can create it.
What is considered to be best practise considering the url params in details api url may get added in future, api may be versioned and all other possibilities for widely used apis?

I'd put my money on creating the link.
There is a perfect explanation why putting id is not enough
DO NOT include just an entity's ID (such as 12) in a response, because
that way you're forcing clients to put together resource URIs
themselves. In order to do that, they would need to have prior
knowledge of what URIs there are, and you're losing control over the
URI space on the server side.
I recommend to read the entire, linked text (approved answer), it's very detailed and got nice resources. As the author mentioned, there is a popular convention how to make connections between resources - HAL. Consider this instead of detailsUrl.
Even if a link to the resource is obvious right now and you decided to put id alone, in other resources after some time it won't be so simple and you will be forced to specify full URL. Then your API won't be consistent. Experience has taught me it's always easier and better for maintenance to send back full link.

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 best practice

I create rest api and I have a POST which has many comments. What is the better url to get post comments
//Get all comments of a post
GET /posts/{postId}/comments
or
GET /comments/{postId}
//Create new comment
POST /posts/{postId}/comments
or
POST /comments/{postId}
A POST has many CATERORY and a CATEGORY can belong to many POST
How I can create a post with ,for example, 3 categories. And how I can connect a specific existing post to a specific existing category
What is the better url to get post comments
REST doesn't care about your spelling conventions for URI -- that's part of the point. So you should use whatever spellings are consistent with your local conventions.
Depending on your API and representations, it may be useful to think about relative references in your hierarchy. For instance, if your base URI is /posts/{postId}/abstract, then the relative reference ../comments can be resolved to /posts/{postId}/comments; but there is no analogous trick to get you from /abstracts/{postId} to /comments/{postId}.
How I can create a post with ,for example, 3 categories
how I can connect a specific existing post to a specific existing category
How would you do it with a web site? Having done that, how would you make the web site machine readable?

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.

RESTful URL for search vs admin

I have a scenario where I have to either
Pull the data from backend as search
Pull the same data from backend to administrate
The URLs I am using are -
/cars
/cars/management
The search can be then subsequently filtered as
/cars?color=blue
The concern that I have is that management is not a resource - it is actually an action. The management page contains links for other functionality associated with car management [add a car/delete a car/list cars/modify cars etc]
Has somebody else faced this issue? Can you let me know your solution?
There is nothing wrong with having a management resource that is a page showing management options for cars. Just because "cars" is the only thing in your database doesn't mean that is the only resource you can present to the user. You could have a resource that is just a form to pick a color (that makes a POST or PUT to the car resource). You could have a resource that is just a form to fill out the address you want the car delivered to. You could have a resource that is just a check box whether you want leather seats or not. You can have as many resources as you like and that make sense, even if all the resources are are pages with forms or links back to the car resource.
Just don't put any verbs in your URLs. You should still be using state transfer using HTTP verbs to change the state of the resources. Don't have a link like
GET /cars/123/deleteCar
on the management page. Instead there might be a link on the management page that (probably using Javascript since browsers have poor native support for HTTP verbs) performs a HTTP request along the lines of
DELETE /cars/123
when the user clicks the link. Something like jQuery can help with that. So long as the management page is using the HTTP verbs to change the state of the resources you are following REST since HTTP is a REST constrained protocol. REST doesn't say don't have actions, it says the actions should be constrained to state transfer.
There is no such concept as a "RESTful URL";
There is no issue with your URLs(/cars, /cars/management)
"/cars/management" is valid resource and it is not an action at all.
The RESTfull way to do this is to use the same URL with different HTTP verbs:
GET /cars for search/listing.
POST /cars for insert.
PUT /cars?id=123 (or /cars/123) for update.
DELETE /cars?id=123 for delete.