Search code examples
springspring-bootcurlpostspring-restcontroller

In Spring Boot 2, how do I construct a curl request to POST (create) an entity when it has foreign keys?


I'm using Spring Boot 2, Java 11, and PostGres 10. I have the following entity. Notice it has a couple of many-to-one foreign key constraints ...

@Data
@Entity
@Table(name = "Cards")
public class Card {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @ManyToOne
    private Occasion occasion;
    
    @Lob
    private byte[] image;
    
    @ManyToOne
    private User author;
}

I have built the following controller for allowing creating and editing of that entity ...

@RestController
@RequestMapping("/api/card")
public class CardController {

    @Autowired
    private CardService cardService;
    
    @GetMapping("/{id}")
    public ResponseEntity<Card> read(@PathVariable("id") UUID id) {
        Card foundCard = cardService.findById(id);
        if (foundCard == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(foundCard);
        }
    }
    
    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public void create(@RequestBody Card card) {
        cardService.save(card);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Card> update(@RequestBody Card card, @PathVariable UUID id) {
        final Card updatedCard = cardService.update(id, card);
        if (updatedCard == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(updatedCard);
        }
    }
    
}

How do I construct a curl request that will submit an entity to my endpoint? I have tried the below ...

curl -v --header "Content-type: application/json" --data '{"occasion_id": "a989055a-b4f4-11ea-a1d1-6a0000c30600", "author_id": "8cfd5756-00c0-478e-a9b5-2ce23e78ea70", "image": "Tom"}' --request POST "http://localhost:8080/api/card"

But this results in a 400 error with the message ...

{"timestamp":"2020-06-23T02:00:53.893+00:00","status":400,"error":"Bad Request","message":"","path":"/api/card"}

Is it possible to adjust my Java code or curl request such that I'm able to successfully create my entity?


Solution

  • Try this:

    curl -v --header "Content-type: application/json" \
    --data '{"occasion": {"id": "a989055a-b4f4-11ea-a1d1-6a0000c30600"}, "author": {"id": "8cfd5756-00c0-478e-a9b5-2ce23e78ea70"}, "image": "<base64 encoded image>"}' \
    --request POST "http://localhost:8080/api/card"
    

    Here is formatted JSON of Card:

    {
      "id": "...",
      "occasion": {
        "id": "...",
        ...
      },
      "image": <base64 encoded image>,
      "author": {
        "id": "...",
        ...
      }
    }