Accessing mediaType in a response (raml-parser-2)


#1

I have a simple RAML definition that parses just fine with the Java raml-parser-2 library. Once I’ve parsed it I’d like to be able to tell which media type has been specified for a response but, though I can navigate to and work with the response, I can’t work out how to access the media type.

#%RAML 1.0
title: Investigate request / response media types
baseUri: https://example.com/media

types:
  type1:
    properties:
      f1: integer
      f2: string

/resource1:
  post:
    body:
      application/json:
        type: type1

  responses:
    200:
      body:
        application/xml:
          type: type1

It feels like it should be easy to get hold of the request and response media types but I just can’t work it out. The following is some Xtend code that I use to navigate a resource.

def void showResponseMediaTypes(Resource resource) {
  resource.methods.forEach[method |
    method.responses.forEach[response |
      response.body.forEach[responseBody |
        logger.info(NLS.bind(
          "{0} - {1} - {2}",
          #[
            method.method + " " + resource.resourcePath,
            Integer.toString(responseBody.code.value),
            << what goes here to extract 'application/xml' from the model >>
          ]
        ))
      ]
    ]
  ]
}

#2

Try the following using the raml-java-parser parser here:

RamlModelResult ramlModelResult = new RamlModelBuilder().buildApi(apiSpec);
		
Api ramlApi = ramlModelResult.getApiV10();
		
System.out.println("body mime type: " + ramlApi.resources().get(0).methods().get(0).body().get(0).name());

In general, the value of a body node is itself a type declaration. This is how it has been implemented atm. Hence, the name of that type declaration is the mime type.


#3

Thanks, Christian. Of course, that worked first time. Although I understood that the value of the body node was a type declaration, I somehow missed that the name of that type declaration might be significant. It seems very obvious now :slight_smile: