REST API support in Spring framework

Learn
1 min readSep 28, 2024

--

I had to make some small changes to some GET APIs that I had in my code base. The level of support that the spring framework (in this case) and frameworks in general provide is what I noticed during this exercise.

PathVariable
When learning the fundamentals of REST a few years back, I remember coming across the concept of path variable, and it’s application. Spring has abstracted that concept into an annotation, and now when I had to add a path variable to enable my APIs to full data against presented IDs, all I had to do was the following

  • Add an “@PathVariable” annotated parameter to the method.
  • Mention the same variable within curly braces in the path URL that was present in the “@GetMapping” annotation that on the method.
  • Then use the variable in the my business method, to invoke the underlying functionality
@GetMapping("/dogstore/puppies/{puppyCode}")
public Puppy getPuppy(@PathVariable String puppyCode) {
return puppyRepository.get(puppyCode);
}

RequestBody

I was passing in static data coming from a sample file for POSTing a resource (say puppy), and now I wanted to use dynamic data instead, that comes from the API call.

What do I do here?

  • Add an “@RequestBody” annotated Puppy variable to the method.
  • Use this variable as a Puppy in the underlying implementation.

The conversion from the json to the Puppy instance is completely transparent to the developer.

public void createPuppy(@RequestBody Puppy puppy) {
puppyRepository.create(puppy);
}

--

--