javaspringrestspring-data-restnested-resources

Spring Data Rest - Include nested resource in _embedded


I'm developing a Spring Boot Application for a shopping list. For this I use Spring Data Rest to export my entities through a REST API.

My Architecture looks like this

I have a ShoppingItem:

public class ShoppingItem {
@Id
@GeneratedValue
private Long id;

@ManyToOne
@JoinColumn(name = "articleId", nullable = false)
private Article article;

private Integer number;

private boolean bought;

public ShoppingItem(){
    this.article = null;
    this.number = 0;
    this.bought = false;
}

}

This shopping item contains an Article which is an exported Resource.

The Article looks like this:

public class Article {

@Id
@GeneratedValue
private Long id;

@Column(unique = true)
private String name;

private Integer price;
}

When i request a ShoppingItem the answer looks like this:

{
  id: 94,
  number: 1,
  bought: false,
  _links: {
    self: {
      href: "https://myDomain.tld/api/shoppingItems/94"
    },
    article: {
      href: "https://myDomain.tld/api/shoppingItems/94/article"
    }
  }
}

Is it possible to include the Article in _embedded when requesting the ShoppingItem so the response looks like this?

{
  id: 94,
  number: 1,
  bought: false,
  _links: {
    self: {
      href: "https://myDomain.tld/api/shoppingItems/94"
    },
    article: {
      href: "https://myDomain.tld/api/shoppingItems/94/article"
    }
  },
  _embedded: {
    article: {
      id: '999',
      name: 'someThing',
      price: '1.99'
    }
  }
}

update 1 When using Accept: application/x-spring-data-verbose+json

The response looks like this:

{
  id: 94
  number: 1
  bought: false
  links: [2]
    0:  {
      rel: "self"
      href: "https://wg.yannic-klem.de/api/shoppingItems/94"
    }-
    1:  {
      rel: "article"
      href: "https://wg.yannic-klem.de/api/shoppingItems/94/article"
    }-
  -
  content: [0]

}

The content-List is always empty :(

update 2:

For more information about my architecture feel free to have a look at my Github repo : https://github.com/Yannic92/ShoppingList/tree/master/src/main/java/de/klem/shopping


Solution

  • Try adding this Accept header when you make the request:

    Accept: application/x-spring-data-verbose+json
    

    Also, take a look at this post where this is explained in details.