- 2 minutes read

My crusade for simplicity goes on. This time, I've run into another trivial and useless mapping. The controller mapped snake_case parameters to camelCase like so:

@GetMapping("/employee") @ResponseStatus(HttpStatus.OK) public EmployeeDto findByName( @RequestParam("first_name") String firstName, @RequestParam("last_name") String lastName) { return employeeService.findEmployeeByFirstName(firstName, lastName); }

There's an easier way. You can add a converter to your project. I've written googled an OncePerRequestFilter converting the requests for you. The source code isn't exciting, so suffice it to point you to my GitHub repository.

With the converter, it doesn't matter if users call your API with camel-case or snake-case parameters. Plus, your API definition is much cleaner:

@GetMapping("/employee") @ResponseStatus(HttpStatus.OK) public EmployeeDto findByName( @RequestParam(String firstName, @RequestParam(String lastName) { return employeeService.findEmployeeByFirstName(firstName, lastName); }

What about JSON objects?

Sometimes, you also want to receive JSON objects with snake-case parameters. There's some Spring magic in store for you. Add this line to your application.properties:

spring.jackson.property-naming-strategy=SNAKE_CASE

Now every JSON object is converted, whether it's an input parameter or a return value. That's different from the converter I've shown before, and it's an application-wide setting. You aren't free to send camel-case and snake-case parameters to your API.

In other words, you must select one style and stick to it. I suppose you can write a more lenient converter as an OncePerRequestFilter, but I didn't try this yet.

Wrapping it up

Remains the question if writing such a converter is a good idea in the first place. Honest answer: I'm not sure. If you're writing a cute microservice, go for it. But as the microservice grows into a full-blown application containing hundreds of REST controllers, I'm not sure. There may be corner cases I didn't think of yet.

On the other hand, as long as you and your customers know what you're doing, give it a try, especially if you're in a greenfield project. This allows Java and JavaScript programmers to use your API using the camel-case notation they're familiar with, and Python programmers can use the snake-case notation.


Comments