7.2.1 Adjusting resource paths and relation names
Actually, Spring Data REST does give you an endpoint for working with tacos. But as clever as Spring Data REST can be, it shows itself to be a tiny bit less awesome in how it exposes the tacos endpoint.
When creating endpoints for Spring Data repositories, Spring Data REST tries to pluralize the associated entity class. For the Ingredient entity, the endpoint is /dataapi/ingredients. For the TacoOrder entity, it’s /data-api/orders. So far, so good.
But sometimes, such as with “taco,” it trips up on a word and the pluralized version isn’t quite right. As it turns out, Spring Data REST pluralized “taco” as “tacoes,” so to make a request for tacos, you must play along and request /data-api/tacoes, as shown here:
$ curl localhost:8080/data-api/tacoes
{
"_embedded" : {
"tacoes" : [ {
"name" : "Carnivore",
"createdAt" : "2018-02-11T17:01:32.999+0000",
"_links" : {
"self" : {
"href" : "http://localhost:8080/data-api/tacoes/2"
},
"taco" : {
"href" : "http://localhost:8080/data-api/tacoes/2"
},
"ingredients" : {
"href" : "http://localhost:8080/data-api/tacoes/2/ingredients"
}
}
}]
},
"page" : {
"size" : 20,
"totalElements" : 3,
"totalPages" : 1,
"number" : 0
}
}You may be wondering how I knew that “taco” would be mispluralized as “tacoes.” As it turns out, Spring Data REST also exposes a home resource that lists links for all exposed endpoints. Just make a GET request to the API base path to get the goods as follows:
$ curl localhost:8080/api
{
"_links" : {
"orders" : {
"href" : "http://localhost:8080/data-api/orders"
},
"ingredients" : {
"href" : "http://localhost:8080/data-api/ingredients"
},
"tacoes" : {
"href" : "http://localhost:8080/data-api/tacoes{?page,size,sort}",
"templated" : true
},
"users" : {
"href" : "http://localhost:8080/data-api/users"
},
"profile" : {
"href" : "http://localhost:8080/data-api/profile"
}
}
}As you can see, the home resource shows the links for all of your entities. Everything looks good, except for the tacoes link, where both the relation name and the URL have that odd pluralization of “taco.”
The good news is that you don’t have to accept this little quirk of Spring Data REST. By adding the following simple annotation to the Taco class, you can tweak both the relation name and that path:
@Data
@Entity
@RestResource(rel="tacos", path="tacos")
public class Taco {
...
}The @RestResource annotation lets you give the entity any relation name and path you want. In this case, you’re setting them both to "tacos". Now when you request the home resource, you see the tacos link with correct pluralization, as shown next:
"tacos" : {
"href" : "http://localhost:8080/data-api/tacos{?page,size,sort}",
"templated" : true
},This also sorts out the path for the endpoint so that you can issue requests against /data-api/tacos to work with taco resources.
Speaking of sorting things out, let’s look at how you can sort the results from Spring Data REST endpoints.
