Search code examples
restweb-servicesapi-design

Loading RESTful objects after authentication


I'd like to know what is the best practice for loading RESTful objects after an authentication procedure.

For example I have an app, that after logging in, it needs to retrieve a list of people, places and some other account-pertinent information. Which of the following would be best practice?

A. After the app calls POST /api/v1/login should it return:

{
    "token": "xxxxx.yyyyyyy.xzzzzzzzzz",
    "persons": [
        {"id": 1, "name": "John"},
        {"id": 2, "name": "Paul"},
        {"id": 3, "name": "George"},
        {"id": 3, "name": "Ringo"}
    ],
    "places": [
        {"id": 1, "name": "London"},
        {"id": 2, "name": "New York"},
    ],
    "lastLogin": "2017-09-10 13:00:00"
}

This method appears to make it easier on the app developers because they do not have to make calls to get the separately. But, it does seem to be tightly coupled.

B. Or should it return just

{
    "token": "xxxxx.yyyyyyy.xzzzzzzzzz"
}

and the app should load the other data separately using for example,

GET /api/v1/persons
GET /api/v1/places
GET /api/v1/lastlogin

This method seems to be cleaner, but it may be harder for the app developers. And there would be some added request overhead, especially if you're loading a lot of different models.

C. Or, should I just have a call named /api/v1/loginWithData which returns the token with the data, and a separate one /api/v1/login which just returns the token? This method has the best of both but it seems it would clutter the api namespace.

I'd really appreciate it if you can send links that would explain so I can learn from them.


Solution

  • Be aware that if we are talking about 3rd party apps, then they should never have the user credentials and auth token. They just get an access key from the user, when they give them some privileges or by more restricted APIs, every single request is signed by the user. If you are talking about sessions and not stateless tokens, then you should check OAuth and the Fielding dissertation to learn the basics.

    If you develop the actual client so it is not a 3rd party app, then the token must travel in the Authorization header or in a cookie instead of the body. I would use the POST /api/v1/auth link which gives you the GET /api/v1/user/136 link to your data source. Or if you use custom MIME type, then return an empty body.