REST method to Create new resource using POST

rest api post example
rest api methods
put vs post vs patch
can we use put instead of post
how to send post request to rest api
rest api get example
put vs patch
rest api post example java
  1. I want to create a new resource using POST at /users { "name" : "Mr. Woods", "age" : 29 }
  2. I do not have ID in the request.

  3. The server would create a new resource with an auto-generated ID (even the same data exists with a different ID which is what it is supposed to do), say 1234

  4. The new resource location /users/1234 has to be returned in the response

  5. Now, should I just return the new ID as return value in the response or the new ID set in the input request and return the whole entity? { "id" : 1234, "name" : "Mr. Woods", "age" : 29 }

  6. Also, when a request hits POST /users but already have an ID provided in the input, do we need to validate for this being null before creating a new one? What would be the Http response code in this case when an ID exists in the input?

Is it okay to use POST for REST API updates?, HTTP POST. Use POST APIs to create new subordinate resources, e.g., a file is subordinate to a directory containing it or a row is subordinate to a database table. Talking strictly in terms of REST, POST methods are used to create a new resource into the collection of resources. Alternatively, use POST to create new resources and provide the client-defined ID in the body representation—presumably to a URI that doesn't include the ID of the resource (see POST below). On successful update, return 200 (or 204 if not returning any content in the body) from a PUT.

I would use spring hateoas (https://spring.io/projects/spring-hateoas) and I would create an object like this:

public class User extends ResourceSupport {
    private Long id;
    private int age;
    private String name;
    //Setter and getter and eventually hashCode and equals
}

then in a controller I would a method like this:

@RequestMapping(value="/users", method={RequestMethod.POST}, produces="application/json")
public ResponseEntity<User> managePerson(@RequestBody User p)
{
  if(p.getId() != null)
  {
    //Update; in this case a 204 http status is enough and no content is required
   Return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null);
  }
  else
  {
   //Save and return the saved objecty with the returned ID and set the new location
   p.add(new Link("/users/"+p.getId()));
   Return ResponseEntity.status(HttpStatus.OK).body(p);
  }

}

When to use PUT or POST, The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. PUT method is idempotent. The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI.

I do not have ID in the request.

You DO NOT need one. You can simply use the Db-SDK for this.

The new resource location /users/1234 has to be returned in the response

It would be better to make it hypermedia driven system HATEOS

Now, should I just return the new ID as return value in the response or the new ID set in the input request and return the whole entity? { "id" : 1234, "name" : "Mr. Woods", "age" : 29 }

Like I said its good to return the complete hypermedia info, so that the clients can refer them without any further modification to make any restful requests

{
    "id": 1234,
    "name": "Mr.Woods",
    "age": 29,
    "address": "/1234/address",
    "some-param": "/path-to-the-resource"
}

Also, when a request hits POST /users but already have an ID provided in the input, do we need to validate for this being null before creating a new one?

Ideally, you should validate it if you are following HTTP specs. Post should always result in the creation of resource. however it's just about following specification nothing stops you if you wish to make your POST idempotent

PUT vs POST: What's the Difference?, The HTTP methods POST and PUT aren't the HTTP equivalent of the CRUD's occasions, to use PUT to create resources, or use POST to update resources. Use PUT when you can update a resource completely through a specific resource. POST is one of the most common methods of HTTP which is used to send data to a server to create/update the resource. Data sent to the server is in the form of either Request Body / Request Parameters which is basically used to create or update the resource on the server.

HTTP Methods – REST API Verbs – REST API Tutorial, In other words, when creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent, assigning an ID  The POST method is used to create new resources. It is used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource. In other words, when creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent, assigning an ID (new resource URI), etc.

REST – PUT vs POST – REST API Tutorial, Now, should I just return the new ID as return value in the response or the new ID set in the input request and return the whole entity? The following is a quick reference for when it is appropriate to use each method. Creates. Use POST to create resources when you do not know the resource identifier. With POST creates, it is best practice to return the status of “201 Created” and the location of the newly created resource, since its location was unknown at the time of submission.

HTTP Methods for RESTful Services, We say that POST method requests are not idempotent and have to be used only for creating resources because we do not have control on  When should we use PUT and when should we use POST? The HTTP methods POST and PUT aren't the HTTP equivalent of the CRUD's create and update. They both serve a different purpose. It's quite possible, valid and even preferred in some occasions, to use PUT to create resources, or use POST to update resources.

Comments
  • I like your last point. Can the ID be the one generated by the database using sequence number generator like a Primary Key?
  • Sure. The resource should be seen as a representation of the data in your information system storage. So if you persist it in a DB, it makes sense to use DB features to generate the IDs.
  • Thanks for the clarification
  • Why would you need to extend DTO class User to ResourceSupport?
  • Thanks but your reply did not answer my last point question. What is Db-SDK?
  • Yes You should validate it if you are following specs. Also you can use specific response code for the same like 400 Bad Request
  • SDK simply refers to the external dependencies (jars). Lot of them support @Id to generate the UUID while creating resource
  • POST should always result in the creation of resource: A server that received a POST request does not necessarily need to create a new resource. According to the specification a POST request is a request to process the payload according to the servers semantics. It is therefore up to the server whether it will create one or not. If it does create a resource representation, however, it should return the URI of the created resource as location header.