Anuja Paradkar
Anuja Paradkar

Reputation: 187

SpringBoot use PUT mapping for create/update resources

Consider following Json body -

{
    "id": 1,
    "userName": "[email protected]",    
    "emails": [
        {
            "id": 69,
            "emailAddress": "[email protected]"
        },
        {
            "emailAddress": "[email protected]"
        }
    ]
}

In this example "User" entity has one-to-many relation with "Email" entity. When I update user, I want to update and/or create emails as well. I understand there should be endpoint for creating/updating emails and there should be one for creating/updating user.

POST /users

PUT /users/{id}

POST /users/{id}/emails

PUT /users/{id}/emails/{emailId}

But I am wondering is it good practise to create/update emails with "PUT /users/{id}" endpoint? Ex: if emails array element has "id" attribute then update existing email. If "id" attribute in emails array is missing then create emails. Is it good way to think.

Upvotes: 0

Views: 1415

Answers (1)

domingo
domingo

Reputation: 177

use POST to create only, and PUT for update only.

POST is a method which is changing a state on server means every time you make a post new record is created.

PUT is idempotent, which means for same request result should be the same for any number of calls.

I would recommend this:

POST /users

creates a user

PUT /users/{id}

updates user that id is {id}. request body contains user info, id is taken from as path variable from url.

POST /users/{id}/emails

creates an email for user id {id}, id is taken from url, email information is in body.

PUT /users/{id}/emails/{emailId}

updates an email for user {id} email with id {emailId}, email id is taken from url, email data from body.

Upvotes: 1

Related Questions