How to design URL to return data from the current user in a REST API? - rest

I have a REST based service where a user can return a list of their own books (this is a private list).
The URL is currently ../api/users/{userId}/books
With each call they will also be supplying an authentication token supplied earlier.
My question(s) is:
Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.
Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?
Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?

Short answer
You could use me in the URL to refer to the current user. With this approach, you would have a URL as following: /users/me/books.
An answer for each question
Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.
You could consider doing something like this: /users/me/books. Where me refers to the current user. It's easier to understand than /users/books, which can be used to return all books from the users.
For some flexibility, besides /users/me/books, you could support /users/{userId}/books.
The URL /users/me can be used to return data from the current user. Many APIs, such as StackExchange, Facebook, Spotify and Google+ adopt this approach.
Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?
I don't think it will break any REST principles, but I think your resources will not be properly indetified. As I answered above, I would use /users/me/books and also support /users/{userId}/books.
Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?
When using the userId in the URL to request private information from a user, there's no harm in checking if the token belongs to the user with the userId included in the URL.

I dont think that removing userId would break any REST principles, because after all, /users and them /books, its a little bit openend to interpretation and REST says basically nothing about it, on the other way if you are going to stay with the id inside the request, you MUST check that the user id is the same as the connected user, anyways, for me the 1 is redundant because you already have that information, plus, every time you are going to make useless checks because anyways the authentified userId is the one that you are going to trust in all cases.
Best Regards

REST is resources oriented so in your point what is the resource user or book. My point of view it's book. And I think you can request this resources
/api/books?user={userid}
But this URL can not solve your permission issue so you have to do it in your code with token information you can get with a OAuth2 protocol or whatever.

Related

REST API architecture

I just started to construct REST API refer to this guide.
It's my first time coustructing REST API architecture, so something ambiguous.
POST vs GET
Before learning about REST API, I choose POST when I don't want form-data being exposed(e.g. user's ID, password, phone number).
But in REST API, POST means 'create new resource' if what I learn is right.
If so, what is the proper method for following case :
'check user's ID is duplicate or not', 'find my id or password'
represent specific action
REST API guide says that use noun to represent.
I Usually named function or method by verb+noun combination(e,g, checkId, findPassword).
Then what is proper(or better) way to represent?
GET /user/check-id
GET /user/id/check
GET /user/id/duplicate
Take a look at the RESTful verbs. POST is definitely used to create something, and GET is a query. That being said, you are absolutely right that GET URL Parameters are often logged all over the place, and you should not use them in GET urls if they contain sensitive data.
To check if a user's ID is a duplicate, I'd do a POST with the user's ID, and return a HTTP 409 code if it already exists.
The find password is a different question. In short, don't do it. You should NEVER, EVER, EVER store a user's password in plain-text. Doing so is negligence in today's computing world. Resetting a password should involve creating a password reset request (A POST to a /user/id/reset), which results in a password request being sent via another channel, but never, ever return a password from a GET request.

Creating user record / profile for first time sign in

I use an authentication service Auth0 to allow users to log into my application. The application is a Q&A platform much like stackoverflow. I store a user profile on my server with information such as: 'about me', votes, preferences, etc.
When new user signs in i need to do 1 of 2 things:
For an existing user - retrieve the user profile from my api server
For a new user - create a new profile on the database
After the user signs in, Auth0(the authentication service) will send me some details(unique id, name and email) about the user but it does not indicate whether this is a new user(a sign up) or a existing user(a sign in).
This is not a complex problem but it would be good to understand best practice. I can think of 2 less than ideal ways to deal with this:
**Solution 1 - GET request **
Send a get request to api server passing the unique id
If a record is found return it
Else create new profile on db and return the new profile
This seems incorrect because the GET request should not be writing to the server.
**Solution 2 - One GET and a conditional POST request **
Send a get request to api server passing the unique id
The server checks the db and returns the profile or an error message
If the api server returns an error message send a post request to create a new profile
Else redirect to the home page
This seems inefficient because we need 2 requests to achieve a simple result.
Can anyone shed some light on what's best practice?
There's an extra option. You can use a rule in Auth0 to send a POST to the /users/create endpoint in your API server when it's the first time the user is logging in, assuming both the user database in Auth0 and in your app are up-to-date.
It would look something like this:
[...]
var loginCount = context.stats.loginsCount;
if (loginCount == 1) {
// send POST to your API and create the user
// most likely you'll want to await for response before moving on with the login flow
}
[...]
If, on the other hand, you're referring to proper API design and how to implement a find-or-create endpoint that's RESTful, maybe this answer is useful.
There seems to be a bit of disagreement on the best approach and some interesting subtleties as discussed in this post: REST Lazy Reference Create GET or POST?
Please read the entire post but I lean towards #Cormac Mulhall and #Blake Mitchell answers:
The client wants the current state of the resource from the server. It is not aware this might mean creating a resource and it does not care one jolt that this is the first time anyone has attempted to get this resource before, nor that the server has to create the resource on its end.
The following quote from The RESTful cookbook provided by #Blake Mitchell makes a subtle distinction which also supports Mulhall's view:
What are idempotent and/or safe methods?
Safe methods are HTTP methods that do not modify resources. For instance, using GET or HEAD on a resource URL, should NEVER change the resource. However, this is not completely true. It means: it won't change the resource representation. It is still possible, that safe methods do change things on a server or resource, but this should not reflect in a different representation.
Finally this key distinction is made in Section 9.1.1 of the HTTP specification:
Naturally, it is not possible to ensure that the server does not
generate side-effects as a result of performing a GET request; in
fact, some dynamic resources consider that a feature. The important
distinction here is that the user did not request the side-effects,
so therefore cannot be held accountable for them.
Going back to the initial question, the above seems to support Solution 1 which is to create the profile on the server if it does not already exist.

REST API Resource Naming Conventions - User or Users (pluralisation)

Long Version
For some, myself included, one of the most painful and headache causing parts of building a REST API is determining the name for each resource and the accompanying endpoints.
Whilst it is, of course, down to personal preference; there are certain things that are encouraged by the community. For example, most people, including me, will pluralise their resource names:
GET /notifications
POST /posts
However, there are cases where pluralising just doesn't seem correct. Consider the following example where user essentially represents the logged in user, not the entire users resource:
Endpoints only relevant to the authenticated user
// Phone Verification
POST /user/phone/request
POST /user/phone/resend
POST /user/phone/verify
// User creation based on authenticated and verified phone
POST /user
// Update authenticated user's profile
PUT /user
// Delete the authenticated user
DELETE /user
// Add/remove the authenticated user's profile image
POST /user/image
DELETE /user/image
// Update the authenticated user's device token
PUT /device/token
Endpoints that access the entire users resource
GET /user
GET /user/{id|self}
In the above example, to me, it feels like the singular user resource name is more suited given on the majority of the endpoints, user refers to the authenticated user, not the entire database of users. But, on the other hand, having GET /user return all users just seems plain wrong...
As a result, I am now torn between user and users - both have strong arguments either way as I see it but would very much welcome another person's opinion on the matter...
Short Version
TLDR - To put it simply, consider the following two endpoints:
// Get all users
GET /users
// Update the authenticated user's device token
PUT /user/device
Both of the above seem correct in my eyes. The problem with the above is that there is no way I am going to have both user and users, it has to be one or the other in my opinion.
The dilemma; Why would I use user when the resource refers to the entire users database? Why would I use users when the resource only refers to the authenticated user?
I cannot get my head around this one... Anyone got any thoughts on this? Or, even better, an alternative solution to my proposed endpoint structure?
Update
After some deep thinking, I have come up with an alternative solution to this but I am still not 100% sure on it as I am not overly keen on using the auth resource name.
Consider this:
// auth = authenticated user
// users = users collection
POST /auth/request
POST /auth/resend
POST /auth/verify
POST /auth
PUT /auth
DELETE /auth
POST /auth/image
DELETE /auth/image
PUT /auth/device/token
GET /users
GET /users/{id}
There are obviously different opinions on this matter, the answer below contains my personal views.
The bottom line is that it's all quite subjective and depends on the way one looks at a certain (type of) resource.
Why would I use user when the resource refers to the entire users
database?
In my opinion, you should never use singular for an endpoint that contains multiple resources.
Some people, however, argue that we should stick to singulars for all resources, mostly for the sake of simplicity and uniformity.
Why would I use users when the resource only refers to the
authenticated user?
You will find quite some different opinions on this, but the consensus and most widely adopted is generally to stick with plurals, except for resources that can only contain a single item (for example, a user profile only containing only one avatar).
Also, since using a singular form for the users resource wouldn't make sense following the above logic, we don't want to mix singular and plural names.
// Update the authenticated user's device token
PUT /user/device
You can interpret 'updating the authenticated user's device token' as follows:
Add a device token to a user entity of the users resource collection.
If your API supports view devices' data of other users, the API can be like /users/$user_id/devices
whereas, when you always have to get the current logged-in user's devices information, the API can simply be /devices (as current user is implied).
i.e IMO, wherever you have only 1 parent resource accessible (say in this case current user is always singular), you can skip that resource in the API URL.

Representation of a User in REST

I'm slowly beginning to unerstand REST and theres one thing thats confusing me .
I understand that most of the things in REST is a "resource" . So i was wondering what kind of a resource would we be referring to in the case of a user signup / login ?
Is it users ? Then does it mean that a POST on users would signup for a new user . If that is the case , then how do i authenticate a user ? a GET on users with an encoded password / username pair?
I'm really confused with this.
I may be COMPLETELY wrong in my understanding given that i'm just starting to understand REST.
Any help is appreciated !
Thanks!
It's a bit of an unusual but common problem for REST. Keep thinking about resources.
When you login you're asking the server to create a session for you to access certain resources. So in this case the resource to create would be a session. So perhaps the url would be /api/sessions and a POST to that url with a session object (which could just be an object consisting of a username or password and perhaps the UUID) would create a session. In true REST you'd probably point to a new session at /api/sessions/{UUID} but in reality (and for security purposes) you'd probably just register a session cookie.
That's my own personal approach to login forms if I were to implement them myself but I always tend to use Spring security for that job so this requirement never really takes much consideration.
I am working on something similar and this is the solution I have taken so far. Any suggestions welcome :)
I have users exclusively for singup and account modifications.
GET /users/{id} gets a user for the profile page for instance
PUT /users creates a new user with username and password. In reality this should send an email with a link to somewhere that confirms the signup with a GET method.
POST /users/{id} modifies the user (for example change password)
DELETE /users/{id}
For authentication I tend to think that the resource I request is the token or the authentication. I have tried to avoid the word "session" because it is supposed to be anti-RESTful, but if you are just creating the illusion of an actual server-side session for your clients, I guess it is fine.
PUT /authentication/ with usename/password returns Set-Cookie with the pair user_id / hashed value. Maybe it should be POST. Not sure
DELETE /authentication/{user_id} just deletes the cookie and the user is signed out. Maybe instead of user_id it should be a unique token_id.
Resources can be created, read, update and deleted using a restful approach, see e.g.:
https://cwiki.apache.org/S2PLUGINS/restful-crud-for-html-methods.html
So if you'd like to administrate you users this would be the restful approach to do so.
If you'd like to authenticate the users which you have in your administration dataset you need
to design or select a restful authentication mechanism see e.g.
http://de.slideshare.net/sullis/oauth-and-rest-web-services
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/
For a jumpstart on these issues you might want to check out dropwizard:
http://dropwizard.codahale.com/
A resource may have one URI or many
but One URI will have exactly one Resource
Therefore, When Authenticating a user, you are addressing a user who is already registered
While when registering, you are addressing the user (resource) which is yet to be registered.
All you need is a way to process it to your SERVER.
THIS is an example taken from SUGARCRM REST web services implementation.
REST is like http requests to your SERVER.
For eg, when implementing REST Web Services.
Every REST Request is going to same File say
www.your_domain.com/Rest.php?json={your_json_method:'method',params:'watever'}
Where in Json is the request you are sending as a parameters
Requesting to authenticate a user
{method:'SignUp', username:'abc', pass:'pass', confirm_pass:'pass'}
Requesting to register a user
{method:'Login', username:'abc', pass:'pass'}
by this way you can have as many params as you want
Remember JSON is not necessory to be used. you can use simple get params for your query

Restful Api: User id in each repository method?

I am new to both .Net & RESTful services.
Here is the object hierarchy I have in the database: Users->Folders->Notes.
The API: GET /api/note/{noteid}
would get mapped to the repository call
NoteRepository::GetNote(userId, noteId)
Notice that I am passing on the userId to make sure that the note belongs to the logged in user for security purpose.
Is this the right approach? Meaning, every repository call would have the first parameter as the userId to check if the object being accessed belongs to the user.
Is there any better approach?
You don't need the User Id since the
GET /api/note/{noteid}
is indeed unique.
A valid scenario for adding the id would be:
GET /api/{userId}/notes
And then if you want a specific note you can:
GET /api/{userId}/notes/{noteId}
I would implement security at the entry level. whether the user has rights to perform a method on that specific resource. A role model approach would be fine.
Regards.
I would also introduce the user id in the API, because of Stateless and Cacheable constraints described in the Wikipedia REST article.
However, if I check Google Tasks REST API, they don't include the user id, same thing for Twitter API, so it seems a trend not to include the user id. If someone can shed some light I would be grateful.
UPDATE: Thinking more about it, if the noteid is unique across all users, there is no need to include the user id, so a GET /api/note/{noteid} is fine.
However, the logical parent in a restful interface would be GET /api/note/ to get a list of all notes, and here I've the objection, since the list would differ according to the user requesting it, making it non cacheable.
As for your dot net part I think that passing the userid among dot net methods is perfectly fine.