Search code examples
javaswagger-codegen

How to set method name prefix in swagger codegen?


(Newbie to Swagger)

In the swagger specification file, the operationId is the name of the operation, corresponding to the HTTP methods.

For example,

 "/pet/findByStatus": {
      "get": {
        "tags": [
          "pet"
        ],
        "summary": "Finds Pets by status",
        "description": "Multiple status values can be provided with comma separated strings",
        "operationId": "findPetsByStatus",

As seen above, operationId = findPetsByStatus. Suppose I want to generate a prefix for all get operations in my java code, with prefix = 'get_'.

For example, I would expect the swagger codegen to produce all operations corresponding to HTTP GET methods with a prefix = 'get_'. Specifically, above, it might generate: get_findPetsByStatus.

Is there a way to tell swagger codegen to prefix methods?

Please note that I want to use swagger-codegen itself and not APIMatic-like alternatives.


Solution

  • Implement AbstractJavaCodegen (or a subclass that implements it) and overload the postProcessOperations function to prepend prefixes to operations (operationId property of the CodegenOperation class). See making-your-own-codegen-modules for instructions on building and running a custom codegen.

    Pseudocode:

    public class MyCodegen extends AbstractJavaCodegen{ \\or 
        [...]
        @Override
        public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
            super.postProcessOperations(objs);
            Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
            if (operations != null) {
                List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
                for (CodegenOperation operation : ops) {
                    if(operation.httpMethod.equals("GET"){
                        operation.operationId = "get_" + operation.operationId;
                    }[...]
                }
            }
            return objs;
        }
    }