Return Swagger JSON from backend service for custom route like /docs

Something we are seeing customers do is include a JSC snip that includes their Open API Specification document such that it can be directly accessed, manipulated or returned by the MP.

That JSC would be saved in a file oasDoc.js and look something like this:

var oasDoc={
    "swagger": "2.0",
    "info": {
        "version": "1.0.0",
        "title": "Swagger Petstore",
        "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
        "termsOfService": "http://swagger.io/terms/",
        "contact": {
            "name": "Swagger API Team"
        },
        "license": {
            "name": "MIT"
        }
    },
    "host": "petstore.swagger.io",
    "basePath": "/api",
    "schemes": [
        "http"
    ],
    "consumes": [
        "application/json"
    ],
    "produces": [
        "application/json"
    ],
    "paths": {
        "/pets": {
            "get": {
                "description": "Returns all pets from the system that the user has access to",
                "produces": [
                    "application/json"
                ],
                "responses": {
                    "200": {
                        "description": "A list of pets.",
                        "schema": {
                            "type": "array",
                            "items": {
                                "$ref": "#/definitions/Pet"
                            }
                        }
                    }
                }
            }
        }
    },
    "definitions": {
        "Pet": {
            "type": "object",
            "required": [
                "id",
                "name"
            ],
            "properties": {
                "id": {
                    "type": "integer",
                    "format": "int64"
                },
                "name": {
                    "type": "string"
                },
                "tag": {
                    "type": "string"
                }
            }
        }
    }
};

This bit of JSC can then be referenced in the Javascript policy as follows:

<Javascript name="jsGetOASDoc.js" timeLimit="200">
    <DisplayName>jsGetOASDoc</DisplayName>
    <ResourceURL>jsc://jsGetOASDoc.js</ResourceURL>
    <IncludeURL>jsc://oasDoc.js</IncludeURL>
</Javascript>

The Javascript to populate a flow variable with the string version of the doc is quite simple:

//jsGetOASDoc.js
//note that if we included the oasDoc.js file we have a variable defined that
//contains the contents

if(oasDoc){
  context.setVariable("oasDoc", JSON.stringify(oasDoc));
}

From here you can simply assign the flow variable “oasDoc” you the response.

Hope this helps!