spring-boot-custom-endpoints-using-regex
Spring Boot - Custom endpoints using RegEx
June 15, 2022
Andrei Saizu

What do you do when REST conventions are seemingly impossible to follow?

Brief

Let's say we have a user management system that we designed using the REST API guidelines.

The URL on which we access a user would be: /users/{userId}

Say your business logic is based on the userId.

  • For users with a userId that starts with 1 you return a type of response or do some logic
  • For users with a userId that starts with 2 you return a different type of response or do a different logic

You don't want change the URL as you would break the REST API conventions, so the client requests should still be sent to /users/{userId}.

Implementation

This is where Spring comes to rescue. ๐Ÿš’

RequestMapping and all its implementations GetMapping, PostMapping, etc. support Regular Expressions so you have even more precision when defining your Controllers.

You can find more details on the official Spring MVC Documentation website.

For our case we can write something like this:

Let's test it with some requests in Postman. ๐Ÿš€

Talk to the team

ASK US SOMETHING OR JUST SAY HELLO, WE'RE HERE.
Contact