URL Format for a PATCH that links two objects

76 Views Asked by At

I'm not sure what the most RESTful + HATEOS way is to achieve my goal.

I want to use a PATCH operation to update the fields of two objects, creating a relationship between them, I'm not convinced that the current way I'm doing it is the most RESTful way of doing it.

For example,

I have an API that manages books and authors.

I have an Author entity with a list of Books.

{
        "authorId": 1,
        "email": "[email protected]",
        "firstName": "f",
        "lastName": "red",
        "links": [
            {
                "rel": "self",
                "href": "http://localhost:8080/authors/1",
            },
            {
                "rel": "books",
                "href": "http://localhost:8080/authors/1/books",
            }
}

and the Book:

{
        "bookId": 1,
        "title": "REST is Hard",
        "links": [
            {
                "rel": "self",
                "href": "http://localhost:8080/books/1",
            },
            {
                "rel": "author",
                "href": "http://localhost:8080/authors/1",
            }
}

The above objects are DTOs. I have a Spring Boot backend that manages relationships - this is only relevant in that the actual entity objects look slightly different, and are a bit leaky I think.

Currently, the API will link a book and an author together when it receives a PATCH against http://localhost:8080/author/1/book/1

The API will link author/1 and book/1 - Spring Boot adds the book/1 entity to a list of books in the author/1 entity and sets the author field of book/1 to `author/1' - i.e this is a bidirectional one (author) to many (books) relationship.

Implementation aside (and I think there are still improvements I can make so that the implementation is better), what's the best way of forming this link via a RESTful call?

REST and HATEOS are chatty enough as it is, and I wanted to avoid having to make two URL calls (i.e. one PATCH to author/1 and another patch to book/1) hence http://localhost:8080/author/1/book/1.

Is there a canonically right 'RESTful' way of doing this? How would you implement this?

0

There are 0 best solutions below