From the course: Creating Your First Spring Boot Microservice

Controlling API exposure

From the course: Creating Your First Spring Boot Microservice

Start my 1-month free trial

Controlling API exposure

- [Instructor] Earlier we saw that you can not only look up entities but also create, update and delete them with HTTP POST, PUT, PATCH and DELETE. But I do not think that we want to allow the public to modify our database in this way. There are two annotations to accomplish this. @RespositoryRestResource is used to control access at the class level and @RestResource is used to control access at the method level. We can also use @RestRepositoryResource to overfly the default endpoint name. In this example, we set TourPackage's endpoint to a different name which is lowercase p packages. So let's go to our code and make these changes. First, we're in TourPackageRepository. And what I need to do is override any methods provided by CrudRepository that would modify a TourPackage. So I'm going to use my IDE to help me generate and override those methods. So I'm going to select the save methods. And the delete methods. And now, I'm going to annotate them with RestResource exported equals false. Okay, now let's do the same in TourRepository. And restrict their access from the outside world. Another way to do this is my using Spring security but that's beyond the scope of this course so this is just something within Spring Data REST that you can do this. Now let's go back to our PackageRepository and we want to rename the endpoint from the default that's generated. So we use the @RepositoryRestResource. And we set the collectionsResourceRel equal to packages. And the path equal to packages. Okay, everything's good there and compiles. Let's run this. And the application's started. Now let's use Postman to do a GET on packages, lowercase p. And that works like a champ. Let's drill down into California Calm. You notice even the embedded href links have the package's name. Make sure we can do a GET on California Calm with packages and now let's test out trying to delete California Calm. I will make one little side note that you couldn't do this anyway because of referential integrity error but we want to have a better status code returned here than a data conflict. So we have a security code response that's Method Not Allowed which is what we wanted.

Contents