Search code examples
node.jsapi-designwebapi

Should login and get profile be two different api endpoints?


I am designing api for mobile application. I am not sure should I have one endpoint login which will return tokens & user profile
Or have two endpoints and after login call getProfile endpoint.
I saw that people mostly use second option but I don't see benefit of that approach?


Solution

  • Thinking in terms of the single-responsibility principle (which basically says "API methods should do one thing really well"), I'd suggest separating these into two separate things:

    1. POST /login would set up a session and return the session ID to be used in subsequent requests.
    2. GET /profile would return profile information provided a valid session ID is provided.

    There are obvious benefits along the "happy path" for combining these, mainly the fact that after a login operation completes, you automatically provide the user with the data they most obviously would want next (who the user is). Why waste an extra API call to find it out, right?

    If that's all your API will ever need to support, then there's no reason to separate these. But there are a couple cases I can think of for why you might want them separate:

    1. What if an existing and already logged-in user wants to fetch the latest profile information? This means you must support GET /profile anyway (or have them POST /login again which is wasteful).
    2. What if profile information is already cached and the POST /login API call is only happening to re-authenticate the user inside the app to complete an action? You'd be wasting bandwidth by sending data that's not needed.

    Additionally, testing is usually a bit easier when you have each API method doing the one thing they imply they do (POST /login logs the user in, GET /profile fetches the current logged-in user's profile).