serverless-aws-documentation model definitions with optional fields?

Question:

I want to define request and response models. I use the Serverless Framework with AWS and everything I’m seeing recommends using serverless-aws-documentation

The README says that I need to have this line in custom.documentation.models.MODELNAME

But they don’t have an example file of models/error.json to use as a baseline.

In the actual example serverless.yml they have a definition like this:

This doesn’t provide enough detail for what I’m trying to do.


My goal is to have a schema defined for an array of string objects, a message and a status code. The message and status code, though, are optional. These could also be part of other models and if possible I’d like to not repeat their definition for each model.

My current attempt is:

I think this is going to do what I want, but how can I have message and statusCode be optional and repeat these two items in my other models?

I’d be happy with either a yml solution I can put in my serverless.yml file or a json file that I can reference.

Answer:

Including a file

In the example given, error.json can contain any valid schema. So something as simple as this is fine:

{"type":"object","properties":{"message":{"type":"string"}}}

It’s also fine to include attributes like $schema and title:

This is especially handy when you have models already defined in AWS, but you don’t have the serverless yaml to build them. You can simply copy the schema out of the AWS console, paste the json into a file, and use the schema: ${file()} syntax mentioned in the question. As far as I can tell anything that you can get the AWS console to accept will work.

DRY

I don’t know of a way to reference models from within other models in a serverless file, but you could use the same approach as the plugin authors, and just put anything you need to reuse outside of the models and somewhere it’s easier to reuse. The plugin authors use commonModelSchemaFragments.

So if you have some fragments like so:

You can reference those fragments in models like this:

Marking attributes optional

You can accomplish this by marking attributes as required. Simply provide a list of all attributes, except the ones you want to be optional. The json schema for that looks like this:

which you would build by using yaml like this in your serverless file:

Note on request validation

Marking attributes required or optional only matters if request body validation is turned on:

Request body validation option in AWS console

I don’t know of a way to turn on request validation using any special serverless syntax. It looks like you can do this in the resources section, but I haven’t tried it. Source.

Leave a Reply