Home > Back-end >  Dynamic REST endpoint creation with Spring Boot
Dynamic REST endpoint creation with Spring Boot

Time:05-19

I'm working on a framework that has a Spring Boot Java layer and a C layer that contains the core logic. The C layer is modular such that many services with unique responsibilities and commands share common components, including a command processor. The command processor communicates with the Java layer (which is also the same for all services) via Thrift RPC.

Currently, users execute commands through a single executeCommand REST endpoint at the Java level by specifying a command name and set of parameters.

POST http://localhost:8388/framework/executeCommand

JSON Body {"commandName": "aCommand", "parameters": {"param1": "value1", "param2": "value2"}}

Is there a way to dynamically generate REST endpoints based on the set of commands provided by the C layer? Ex... each command would have an endpoint such as

POST http://localhost:8388/framework/aCommand

JSON Body {"parameters": {"param1": "value1", "param2": "value2"}}

OR

GET http://localhost:8388/framework/aCommand?param1=value1

Ex... at startup, the Java layer would query the C layer for the set of commands and other relevant information such as the appropriate REST method. With this information the Java layer would generate an endpoint for each command.

Thanks!

CodePudding user response:

You could use a path variable in your REST controller to accept different command types, something like so:

@RestController
@RequestMapping("/command")
@RequiredArgsConstructor
class CommandController {

    private final CommandService commandService;

    @PutMapping("/{commandType}")
    public CommandResult handleCommand(@PathVariable("commandType") String commandType,
                                       @RequestParam Map<String, String> params) {
        return commandService.execute(commandType, params);
    }
}

(Here CommandService is a service that loads available commands at startup and then validates and executes a requested command).

You could then run a command with a request like PUT http://localhost:8080/command/someCommand?param1=value1&param2=value2

UPDATE

Some solutions for the clarified requirements (dynamic REST controller creation):

  • Related