I am using Postman and learning how to do a POST request to add a new Item
to the cart and write it to the database. The Java
code for the item is:
public class Item {
private int id;
private String name;
private String description;
private LocalDate expired;
}
with getters and setters.
In Spring
framework I have the next method:
@PostMapping
public void add(@RequestBody Item newItem) {
itemSer.addNewItem(newItem);
}
Using postman in the body part I selected raw
-> json
: (its the result of a GET
request.)
{
"id": 2,
"name": "postman",
"description": "postman",
"expired": {
"year": 1700,
"month": "NOVEMBER",
"monthValue": 11,
"dayOfMonth": 21,
"leapYear": false,
"dayOfWeek": "WEDNESDAY",
"dayOfYear": 325,
"era": "CE",
"chronology": {
"id": "ISO",
"calendarType": "iso8601",
"isoBased": true
}
}
}
Postman give me an 405
error but I have no idea why, I am using tomcat 9. Is there same problem also for the date format?
EDIT:
So the problem is only on the LocalDate
, I have to format in a way that is readable by java with a Post request.
Snooping around I did find this solution: How to send Date in REST API in POST method
(if you are using maven)
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
the add in the AppConfig di spring:
@Bean
public ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
and int the Itmes
class over the LocalDate
variable:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate date;
the post is now just looks like the next:
{
"id": 2,
"name": "postman",
"description": "postman",
"expired": "2030-01-02"
}
I still have a question, reading this i did understand generally how it works, where can I find some other info on how this works? or if someone want to explain I am happy to listen.