Search code examples
swaggerswagger-codegen

swagger-codegen and $ref attribute with spaces


I'm currently looking into using our swagger-file that's mainly used for documentation to be used to generate client side SDKs.

I have noticed that our swagger file (that's in swagger 2.0 json format) contains references to defentitions like this:

"$ref":"#/definitions/My%20Awesome%20Object"

When I generate C# SDK, this translates to code that looks something like this:

ApiResponse<My20Awesome20Object>

Removing the %20 from the swagger file solves this issue, but talking to the web backend guys, they say that it's in there as it won't validate otherwise, and I can't find the refernce, but I remember that I found a reference in the swagger-codegen pages that states that the $ref field should be URI encoded, so it seems to be correct.

My current plan is to do a simple script that just strips out the %20 to generate proper references to classes. But that feels like a ugly workaround. Do you have any suggestion how to solve this in a nicer way that is complient to the standard while getting proper code?

Cheers, Markus


Solution

  • $ref values are URIs. %20 is there because the schema names in the definitions section contain spaces, like so:

    "definitions": {
      "My Awesome Object": {    // <---   $ref: "#/definitions/My%20Awesome%20Object"
        "type": "object",
        ...
      }
    }
    

    Some tools have problems with handling non-alphanumeric characters in schema names; this includes spaces, < >, «‎ » and the like. Maybe this was why OpenAPI 3.0 restricted valid component names to A-Z a-z 0-9 - . _.

    The best fix is to both remove %20 from the $refs AND remove spaces from the schema names in the definitions section. This way the schema names will be forward-compatible with OpenAPI 3.0 if/when you migrate to a newer OpenAPI version.