I am currently working through a Spring tutorial on REST (whole tutorial is at spring.io/guides/tutorials/rest/). I am pretty sure I have followed the guide accurately. I have the following code for the EmployeeController:
package com.example.buildingrest;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
class EmployeeController {
private final EmployeeRepository repository;
EmployeeController(EmployeeRepository repository) {
this.repository = repository;
}
// Aggregate root
@GetMapping("/employees")
List<Employee> all() {
return repository.findAll();
}
@PostMapping("/employees")
Employee newEmployee(@RequestBody Employee newEmployee) {
return repository.save(newEmployee);
}
// Single item
@GetMapping("/employees/{id}")
Employee one(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
}
@PutMapping("/employees/{id}")
Employee replaceEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) {
return repository.findById(id)
.map(employee -> {
employee.setName(newEmployee.getName());
employee.setRole(newEmployee.getRole());
return repository.save(employee);
})
.orElseGet(() -> {
newEmployee.setId(id);
return repository.save(newEmployee);
});
}
@DeleteMapping("/employees/{id}")
void deleteEmployee(@PathVariable Long id) {
repository.deleteById(id);
}
}
When I do a CURL command to get all employees I am successful, and when I do a CURL command to get one employee by id, I am successful. The problem is when I try to POST a new employee. I am using the following command, which comes from the tutorial:
curl -X POST localhost:8080/employees -H 'Content-type:application/json' -d '{"name": "Samwise Gamgee", "role": "gardener"}'
I get the following error:
{"timestamp":"2020-03-20T13:28:56.244+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not
supported","path":"/employees"}curl: (6) Could not resolve host: Samwise Gamgee,
curl: (6) Could not resolve host: role
curl: (3) [globbing] unmatched close brace/bracket in column 9
As far as the unmatched close brace/bracket, I have looked at the code and the CURL command up and down and cannot find it. As far as the Unsupported Media Type, I don't understand why it is stating x-www-form-urlencoded when I have been using JSON for the whole application. And I have copied the curl command straight from the tutorial.
Any ideas what is wrong?