2

By default, Spring data REST use camelCase for endpoint names.

For example, if the repository is

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Integer> {

    List<User> findByUsername(@Param("username") String username);

}

Then the endpoint is http://localhost:8080/users/search/findByUsername?username=test

How can I customize the endpoint so it use snake_case, became like this: http://localhost:8080/users/search/find_by_username?username=test

Or even different method name

  • change find_by_username : http://localhost:8080/users/search/by_username?username=test
  • (stripping the find_by_username): http://localhost:8080/users/search?username=test

Thanks

0

1 Answer 1

4

The @RestResource annotation also gives us the ability to customize the URL path mapped to a repository method and the link id in the JSON returned by the HATEOAS resource discovery.

To do that, we use the optional parameters of the annotation:

  • path for the URL path
  • rel for the link id

By executing a cUrl to http://localhost:8080/users/search/, we can now see our new method listed with other resources:

{
  "_links": {
    "findByUsername": {
      "href": "http://localhost:8080/users/search/findByUsername{?username}"
    },
    "self": {
      "href": "http://localhost:8080/users/search/"
    }
  }
}

So to customize the rest url endpoint, we can simply add the @RestResource annotation:

@RestResource(path = "byUsername", rel = "customFindMethod")
 List<User> findByUsername(@Param("username") String username);

If we do the resource discovery again, the resulting JSON will confirm our changes:

{
  "_links": {
    "customFindMethod": {
      "href": "http://localhost:8080/users/search/byUsername{?username}",
      "templated": true
    },
    "self": {
      "href": "http://localhost:8080/users/search/"
    }
  }
}

For more details you can check her

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.