REST URI Design for resources that belong to a specific user - rest

Assume I want to create a very simple todolist RESTful API, where each user owns a list of todos. The user is already authenticated over http BASIC or DIGEST.
At this point I am not sure what the URL scheme should look like.
Would it be:
http://servername/todos/
where my server filters the appropriate todos according to the authentification given to me by the http header.
Or should I include the username in the URI instead:
http://servername/users/username/todos/
On some websites I have even seen that they hand over the user name as a parameter like this:
http://servername/todos?username=babsi
As far as I can tell all three choices are stateless as I always receive the username, but just over different sources. From what I can tell to make sure that the URI is accessed by the proper user I always need to check the http header anyways. So which of the ways would you consider the best URI design in REST or should I do in a different way entirely?

You can use the following:
http://servername/todos/ GET list all todos
http://servername/users/ GET list all users
http://servername/users/{user_id}/ GET list an user
http://servername/users/{user_id}/todos/ GET list all todos for an user
I think the point here is how you want to design the relationships between your resources, if a todo just can exist in the context of an user use a hierarchy like approach as above.
As general rule i usually follow this:
Use path variables to encode hierarchy: /parent/child
Put punctuation characters in path variables to avoid implying hierarchy where
none exists: /parent/child1;child2
Use query variables to imply inputs into an algorithm, for
example: /search?q=jellyfish&start=20

Having the username in the URL depends on what you want to do (if anything at all) when you receive a request where the username in the URL does not match the authentication. If you want to re-authorize the user in this situation then yes - it's OK to have the username in the URL, otherwise it's OK to have it just in your header or other authentication scheme if there is no such need.
One fairly common example of a valid requirement would be if you have to have a main user (or group of such users) that can impersonate other users.

When the user in question is always the user who is holding the authentication token, then use something like "me" in your path.
http://example.com/users/me/<path-to-inner-resource>
Otherwise, user should be treated just like any other resource in your system, in which case the resource identifier for that user becomes a part of the path.
http://example.com/users/<id>/<path-to-inner-resource>
Take a look at Twitter APIs as an example.
https://developer.twitter.com/en/docs/twitter-api/users/follows/quick-start/follows-lookup

Related

Sub routing best practices

I am building an api which has a route: /market/items/{category}, it returns items from a category. If a user clicks on an item I have a route /item/{id}/ which returns information about the item. I'm wondering if this is a bad practice when creating a restful api. because often I would see routes like /market/items/{category}/{id}. What do you think?
If only the id is needed in order to retrieve the item (in other words, the id by itself uniquely identifies the item without any other information), then there's no reason to require a category in the URL also so this:
/item/{id}/
would be just fine for a restful API.
If, on the other hand, there are multiple types of items, each with overlapping item identifiers, then you may need something else in the URL to uniquely identify which type of item and thus which pool of item identifiers to look in.
One reason you may see some web sites doing something like this in their web page URLs:
/market/items/{category}/{id}
is for search indexing where they want the category name to be associated with the item for purposes of search engine indexing. But, if this is just a restful API, not visible web pages, then you probably aren't trying to optimize that for search hits.

REST: nested resource url when you don't want the parent ID visible

I read that the route for getting a nested resource in REST should look like this
/articles/:articleId/comments
The owner (:articleId) of the child resource will be visible.
But what if you have an owner that you don't want the client to know about?
For example, let's say I have an app where users have anonymous posts. I wouldn't want other users to see the client fetching the post by /users/123/post/321 because users could identify who wrote the post from the id and it wouldn't be anonymous.
Is the id necessary? Is it ok to instead do /users/posts/321 if all posts have a unique id?
There are no actual requirements for the URL format. It can be whatever you'd like it to be.
If it were me, I would use simply /posts/321 and leave users out of it, since a particular user isn't specified in your URL at all. I think that's the clearest way to handle it in your case.

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 would be a RESTful URI for retrieving all Products created by a particular Client? (you have the client's ID)

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}

What is an appropriate URI for a user registration form in a RESTful setting?

I'm working on a web application under Laravel and I'm trying to be as RESTful as I can, but admittedly this is the first time writing this kind of application.
I'm specifically trying to create RESTful URI's for the controllers of my project.
So far I have (in pseudo code)...
URI Goes to... Desc
--- ---------- ----
/ GET
if logged in dashboard GET
else frontpage GET
login GET login GET login form
login POST login POST attempt login
login DELETE login DELETE logout
user GET
if logged in user GET show user control panel
else login GET redirect to the login w/ error
So far so good, but how should I go about creating a new user?
I had a couple of ideas, for example:
URI Goes to... Desc
--- ---------- ----
user/create GET register GET show the create user form
user/create POST register POST attempt to create a new user
So we use a register controller here, but we hide it behind the user URI.
Advantage here is that we stick to HTTP actions (just GET and POST), and we create a nice readable URI.
Disadvantage is that our URI does not accurately represent our controller.
URI Goes to... Desc
--- ---------- ----
register GET register GET show the create user form
register POST register POST attempt to create a new user
In this case we have A. used HTTP controls, B. created a URI that is a representation of our controller, and C. created a nice readable URI, but unfortunately our URI isn't really representational of the data. In no way is this register controller representative of our user.
Which is more appropriate? Why? Is there a better way? Thanks!
In those cases I would create a Route::resource for users, like so:
Route::resource('user', 'UsersController');
and to optimize user readability add:
Route::get('/signup', 'UsersController#create');
For logins I would create a Route::resource for sessions, like so:
Route::resource('sessions', 'SessionsController');
and to again, optimize user readability add:
Route::get('/login', 'SessionsController#create');
Using resources makes some methods ready for you, but you are not using all of them.
So you might want to reduce that to the ones you use, only. Like so:
Route::resource('sessions', 'SessionsController', ['only' => ['create', 'store', 'destroy']);
Hope this helps you further.
In your case I will go for the user readability. I always prefer to have something like example.com/signup, example.com/register to show the form that handles the creation of the user. As a user, the URL tells me that I'm in the right place, even if the controller that handles this is totally different. The middle URL (where you will post your data) is not important because it will not displayed to your users: you will redirect them to the create form or the success page.
If you were building an API (the intended users are developers) I will go for a POST users, because developers should be familiar with REST principles.