1

I have an endpoint that requests the current logged in user.

GET /user/current source

If a user is found, the server sends 200 OK and the user object.

But what if no one is logged in? Should the server send back 200 Ok with an empty object?

This post asked a similar question:

For example you run a GET request for users/9 but there is no user with id #9. Which is the best response code?

The top answer was 404 Not Found. But this doesn't seem correct to me for a current user request with no logged in user. In this case the answer was found- the answer is that no user is logged in.

Dashiell Rose Bark-Huss
  • 2,173
  • 3
  • 28
  • 48

2 Answers2

1

I believe you want 401 Unauthorized

JoelFan
  • 37,465
  • 35
  • 132
  • 205
  • Oh yeah sort of makes sense, although I thought 401 were for protected routes and I hadn't really thought of it as a protected route. The 'user/current' endpoint is for helping the frontend know when to render an 'edit profile' button for example. Do you think it still makes sense to put to 401 Unauthorized in that case? – Dashiell Rose Bark-Huss Nov 25 '20 at 22:05
  • `RFC 7235` states: "The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource." It's very general. – JoelFan Nov 25 '20 at 22:12
  • If you want to strictly conform to the HTTP standard, whenever you respond with a 401 you must also include a `WWW-Authenticate` header that directs the client with how to resolve the authentication problem, with a value like: `Basic realm="Please login"` – JoelFan Nov 25 '20 at 22:16
1

401 would be valid only when authorization is required for making that call to that end point and it was not provided.

If that's an endpoint which doesn't require authentication then 404 is correct

You can also use 200 with current user as null if the response is usually a json string . If it's usually a json array return empty array with status 200 .

You can also use 204 no content

PDHide
  • 18,113
  • 2
  • 31
  • 46
  • Why are you not recommending `403 Forbidden`? – JoelFan Nov 30 '20 at 20:42
  • @Joel because that's a open api that doesn't have any authorization or authentication , 401 for authentication error and 403 is for authorization errors – PDHide Dec 01 '20 at 02:35
  • Aa this api doesn't have authorization and authentication , both 401 and 403 is not applicable – PDHide Dec 01 '20 at 02:36