3

I give an common user login/logout example about discussing HTTP method and status code. I hope It can help people to understand easily.


Traditional no restful api design:

When user login/logout a website, it's sure to access backend service by HTTP request of POST method.

It's beyond question.


But if I follow restful api design pattern, is still it be designed?

My thought is:

  • Login

Login will generate a token key when user login. I think it's a creation action for database because generating a token key, so should it return 201 Created status code?

  • Logout

Relatively, Logout will delete the token key when user send his token and do logout. I think it's a deletion action for db because deleting the token key, so should it return 204 No content status code?

Although I think it maybe fits in with HTTP method meaning, if I will offer or share this API design, does it make other developer confuse?

I don't know this idea is or isn't good. I want to listen your opinion.

2 Answers 2

3

I don't think that the scenario that you describe would be confusing to developers. In my experience, it's rare that you would have special handling around a 200, a 201, or a 204 whereas the typical case is code >= 200 && code < 300. Your logic is not unsound. If you're returning a token, a 201 would be reasonable and a 204 if you're not returning any content.

However, generating a token is really a side-effect of you logging in. POST /login is not creating a login resource like POST /items would be creating an item, and API tokens are not typical resources. For that reason, a 200 OK would be more appropriate since you're really just giving the user permission to move forward to protected resources, albeit by creating a token. If you look around for authentication examples, it seems that sending a 200 or redirecting the user are the typical solutions.

Sign up to request clarification or add additional context in comments.

1 Comment

These lines generating a token is really a side-effect of you logging in standout - reminding of Separation of Concern for API design.
0

Both login and logout should be POST because GET may get cached under some circumstances. On logout success server may set response status 302 redirect and header location: url_to_visit_after_logout

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.