I'm learning Spring Boot rn and I'm getting errors on my way when I'm trying to use POST method.
HTTP code is 400.
Here is the code of my rest controller c:
package com.example.carsapi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.awt.*;
import java.util.Optional;
@RestController
@RequestMapping("/cars")
public class CarRestController {
private final CarService carService;
@Autowired
public CarRestController(CarService carService) {
this.carService = carService;
}
@GetMapping
public ResponseEntity<List> getCars(){
return new ResponseEntity(carService.findAllCars(), HttpStatus.OK);
}
@GetMapping(value = "/id/{id}")
public ResponseEntity<List> getCarById(@PathVariable Integer id){
Optional<CarDTO> found = carService.findAllCars().stream().filter(car -> car.getCarId() == id).findFirst();
if(found.isPresent()){
return new ResponseEntity(found.get(), HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@GetMapping(value = "/color/{color}")
public ResponseEntity<List> getCarByColor(@PathVariable String color){
Optional<CarDTO> found = carService.findAllCars().stream().filter(car -> car.getColor().equals(color)).findFirst();
if(found.isPresent()){
return new ResponseEntity(found.get(), HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@PostMapping(value = "/add")
public ResponseEntity addCar(@RequestBody CarDTO car){
carService.findAllCars().add(car);
return new ResponseEntity(HttpStatus.CREATED);
}
}
And there is my JSON code which I'm using:
[
{
"carId": 3,
"carBrand": "Audi",
"carModel": "RS6",
"color": "red"
}
]
Hope you'll help me I had even tried with @RequestParam
, getting all of the values like id
, brand
, model
and color
and then adding a new object with these values which I've got from the query but it still didn't work.