Defining conditional body for POST


#1

Hello,
I’m designing my first API in RAML. I have an existing API that accepts POST method with multipart/form-data (or) an object (defined by xml or son). I tried to define them in the post/body as below but how do we specify that request must specify either one of these (multipart/form-data) or object and not all of them?

  post:
    body:
      multipart/form-data:
      application/xml:
      application/json:

Thanks.


#2

The way you have it should work… you are defining it to indicate that the POST request can send either form-data, xml or json. Below each you would specify the schema: or type: (depending on RAML 0.8 or 1.0), and an example or two perhaps, maybe a description for documentation purposes as well.


#3

Thank you. yes I see that now.

But what if I want to define “queryparameters” in accordance to the media type posted.
For example: a parameter “userId” is required for multipart/form-data where as it is not required for application/xml. How can I define this. Currently If I define “required: false”, it would mean that multipart/form-data can be accepted without “userId” but not valid as per application. How to enforce this rule in spec ?


#4

In RAML 0.8 you can specify the required attribute for query parameters as you noted, however, as you also noted for different media types that wouldnt be possible to specify required for one and not required for another.

The right way to do it is not specify required, in my opinion, and in your code, if a query parameter is there, use it. If for example you require it for the json and it is not there, return a 400 Bad Request. If it is not required, and is part of the request, and lets say XML could care less, simply ignore the query parameter in your server side code. Also, use the description fields of each media type to document that the query parameter is required or not, optional, etc. It may not be possible to enforce all rules in your particular scenario, but you can go a long way in helping would be consumers of the API understand how to use your resource with different media types and hopefully they are intelligent enough to use it correctly. Of course, you probably want to set up some Postman automated tests (or something similar) to try out all scenarios yourself before you ever release the API to make sure you have all corner cases covered.


#5

Yes the application can handle it and the consumers has to be intelligent enough! But It would have been better to provide some kind of restriction in the spec itself to not so “intelligent consumers”.

Thanks for your response.