Auro Auro - 1 month ago 5
JSON Question

POST request to RESTful API always results in HTTP 400 Syntactically incorrect error message

I've implemented a RESTful API in my web server using Jersey to handle simple

POST
requests.

The method is given below: -

@Path("create")
public class Create {

.........

@POST
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public StatusResponse createPost(
@PathParam("id") final String identifier,
final PostInfo postInfo) {

// Does its work

}


And following is the PostInfo.java : -

public class PostInfo {

private String message;
private String date;

public PostInfo() {

message = null;
date = null;

}

/**
* @return the message
*/
public String getMessage() {
return message;
}

/**
* @return the date
*/
public String getDate() {
return date;
}

/**
* @param message the message to set
*/
public void setMessage(final String message) {
this.message = message;
}

/**
* @param date the date to set
*/
public void setDate(final String date) {
this.date = date;
}

}


Problem here is, every time I make a POST request with JSON elements, it results in

HTTP Status 400 - Bad Request The request sent by the client was syntactically incorrect.


I had a look at a few others posts having similar problem (this and this), but they were of no help.

I'm using Chrome's POSTMan to make the request at the following URL with the following body:

URL:
wallpostapi.herokuapp.com/webapi/create/xyz123@123.com

Body :

{
"message" : "WHADDUP DAWG???"
"date" : "2016-09-09 11:00:20"
}

Answer

The syntax of your JSON is not correct, a comma missing. Please try the following JSON.

{
    "message": "WHADDUP DAWG???",
    "date": "2016-09-09 11:00:20"
}

Further, the best practice is to use nouns but no verbs in the URI like,

http://wallpostapi.herokuapp.com/webapi/v1/info

The ID can be send in the header as an optional parameter or can be auto generated for create.

id   xyz123@123.com

The name of your create method should be,

public StatusResponse createInfo(
            @HeaderParam("id") final String identifier,
            final PostInfo  postInfo {
        // Does its work 
}