Correct way of defining REST endpoints for user management
Asked Answered
M

2

7

I have a typical user management module for which I want create REST APIs. User should be able to access his/her details but shouldn't be allowed to access other user details. Being an administrator user should be able to fetch any user or remove any user.

This is how I am planning to create URL end points, any suggestions ?

# To create/register user
POST /api/users/
# or
POST /api/register/

# To get all users
# This will be allowed to access only by admins.
GET /api/users/

# To get current user.
# For admin, allowed
# For regular user, id will be validated against userid stored in the session.
GET /api/users/<id>/

# To update current user.
# This id will be validated against userid stored in the session.
PUT /api/users/<id>/

# To delete current user.
# For admin, allowed
# This id will be validated against userid stored in the session.
DELETE /api/users/<id>/

# Login
POST /api/login/

# Logout
GET /api/logout/

Thank you

Malcolm answered 24/9, 2016 at 13:27 Comment(2)
Try to understand the HATEOAS constraint. en.wikipedia.org/wiki/HATEOAS REST is not about designing endpoints, it is about designing hyperlinks the client can follow. By REST you decouple the client from the endpoint structure, so you can change for example the URI any time without breaking the client... The client uses the link relation to decide what to do with a hyperlink. en.wikipedia.org/wiki/Link_relation dpkg is right about the statelessness constraint, there must not be a login/logout in the REST API.Redford
Ultimately this is a not a REST or HATEOS question. This is a question about authentication and authorization.Garling
G
10

I think you've got the endpoint scheme pretty good.. only thing is the context will be the passed-in user (from the url path) and not current user.

# To create
POST /api/users

# To get all users
GET /api/users

# To get particular user.
GET /api/users/<id>

# To update particular user.
PUT /api/users/<id>

# To delete particular user
DELETE /api/users/<id>
Girvin answered 24/9, 2016 at 14:23 Comment(2)
Thanks for the suggestions :)Malcolm
Just being picky, but I've never liked the idea that PUT is an update in REST. It's a create or replace, or rather a 'SET'. You could call it an update, but it's a complete update. If you're just setting a part of it, then it's really a PATCH.Propitious
G
5

A general recommendation will be to make your REST API stateless - i.e. if instead of keeping a userId in the api session, the caller sends the identification (with the auth header) in the api request. The api will then retrieve the user from the header, check if that user has sufficient permissions before doing any core operation (some sort of interceptor can be used for that).

Check this for more details - https://mcmap.net/q/55232/-do-sessions-really-violate-restfulness

Girvin answered 24/9, 2016 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.