In this example we will look at how to use the Middy validator middleware with a serverless API to validate request and response schemas.

Requirements

What is Middy

Middy is a very simple middleware engine that allows you to simplify your AWS Lambda code when using Node.js. It allows you to focus on the strict business logic of your Lambda function and then attach additional common elements like authentication, authorization, validation, serialization, etc. in a modular and reusable way by decorating the main business logic.

Create an SST app

Let’s start by creating an SST app.

$ npx create-serverless-stack@latest middy-validator
$ cd middy-validator

By default our app will be deployed to the us-east-1 AWS region. This can be changed in the sst.json in your project root.

{
  "name": "middy-validator",
  "region": "us-east-1",
  "main": "stacks/index.js"
}

Project layout

An SST app is made up of a couple of parts.

  1. stacks/ — App Infrastructure

    The code that describes the infrastructure of your serverless app is placed in the stacks/ directory of your project. SST uses AWS CDK, to create the infrastructure.

  2. src/ — App Code

    The code that’s run when your API is invoked is placed in the src/ directory of your project.

Create our infrastructure

Our app is made up of a simple API. The API will read two variables from the request and return a greeting message as a response.

Creating our API

Let’s start by adding the API.

Add this in stacks/MyStack.js.

import * as sst from "@serverless-stack/resources";

export default class MyStack extends sst.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    // Create a HTTP API
    const api = new sst.Api(this, "Api", {
      routes: {
        "POST /": "src/lambda.handler",
      },
    });

    // Show the endpoint in the output
    this.addOutputs({
      "ApiEndpoint": api.url,
    });
  }
}

We are using the SST Api construct to create our API. It simply has one endpoint (the root). When we make a POST request to this endpoint the Lambda function called handler in src/lambda.js will get invoked.

Replace the code in src/lambda.js with:

export async function handler(event) {
  const { fname, lname } = JSON.parse(event.body);
  return {
    statusCode: 200,
    headers: { "Content-Type": "text/plain" },
    body: `Hello, ${fname}-${lname}.`,
  };
}

We are reading two variables fname and lname from the event body and returning a simple greeting message.

Let’s test what we have so far.

Starting your dev environment

SST features a Live Lambda Development environment that allows you to work on your serverless apps live.

$ npx sst start

The first time you run this command it’ll take a couple of minutes to deploy your app and a debug stack to power the Live Lambda Development environment.

===============
 Deploying app
===============

Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-middy-validator-my-stack: deploying...

 ✅  dev-middy-validator-my-stack


Stack dev-middy-validator-my-stack
  Status: deployed
  Outputs:
    ApiEndpoint: https://bqoc5prkna.execute-api.us-east-1.amazonaws.com

The ApiEndpoint is the API we just created.

Let’s test our endpoint using Insomnia.

Insomnia request with correct schema

As you can see the endpoint is working as expected. We sent mani and teja as our fname and lname respectively and got Hello, mani-teja as the response.

Now let’s remove lname from the request object and see what happens.

Insomnia request with incorrect schema

You’ll notice that the endpoint is working fine but it returned undefined for lname. Since we’d only sent the fname in the request, so it returned undefined in the place of lname.

In a production app it can be difficult to catch these issues. We’d like to explicitly throw an error when there is a missing parameter in the request body.

Setting up our Middy middleware

To fix this let’s use the Middy validator middleware to validate our API.

Run the following in the project root.

$ npm install --save @middy/core @middy/http-json-body-parser @middy/http-error-handler @middy/validator ajv

Let’s understand what the above packages are.

package explanation
@middy/core The core package of the Middy framework.
@middy/http-json-body-parser A middleware that parses HTTP requests with a JSON body and converts the body into an object.
@middy/http-error-handler A middleware that handles uncaught errors that contain the properties statusCode (number) and message (string) and creates a proper HTTP response for them (using the message and the status code provided by the error object).
@middy/validator A middleware that validates incoming events and outgoing responses against custom schemas defined with the JSON schema syntax.
ajv AJV stands for “Another JSON Schema Validator” and is the fastest validator for JSON schemas.

Adding request validation

Replace src/lambda.js with the following.

import middy from "@middy/core";
import validator from "@middy/validator";
import jsonBodyParser from "@middy/http-json-body-parser";
import Ajv from "ajv";

const ajv = new Ajv();

const baseHandler = (event) => {
  // You don't need JSON.parse since we are using the jsonBodyParser middleware
  const { fname, lname } = event.body;
  return {
    statusCode: 200,
    headers: { "Content-Type": "text/plain" },
    body: `Hello, ${fname}-${lname}.`,
  };
};

const inputSchema = {
  type: "object",
  properties: {
    body: {
      type: "object",
      properties: {
        fname: { type: "string" },
        lname: { type: "string" },
      },
      required: ["fname", "lname"],
    },
  },
};

const handler = middy(baseHandler)
  .use(jsonBodyParser())
  .use(
    validator({
      inputSchema: ajv.compile(inputSchema),
    })
  )
  .use(httpErrorHandler());

export { handler };

Here we are creating an inputSchema and precompiling it with Ajv. We are explicitly setting that fname and lname are required.

Now open Insomnia and send a request.

Insomnia request with Middy schema request validation

Great! The server throws a 400 Bad request error to let us know that something is wrong.

Adding response validation

While we are here, let’s add response validation as well.

Replace src/lambda.js with this:

import middy from "@middy/core";
import validator from "@middy/validator";
import httpErrorHandler from "@middy/http-error-handler";
import jsonBodyParser from "@middy/http-json-body-parser";
import Ajv from "ajv";

const ajv = new Ajv();

const baseHandler = (event) => {
  const { fname, lname } = event.body;
  return {
    statusCode: 200,
    headers: { "Content-Type": "text/plain" },
    body: `Hello, ${fname}-${lname}.`,
  };
};

const inputSchema = {
  type: "object",
  properties: {
    body: {
      type: "object",
      properties: {
        fname: { type: "string" },
        lname: { type: "string" },
      },
      required: ["fname", "lname"],
    },
  },
};

const outputSchema = {
  type: "object",
  required: ["body", "statusCode"],
  properties: {
    body: {
      type: "string",
    },
    statusCode: {
      type: "number",
    },
    headers: {
      type: "object",
    },
  },
};

const handler = middy(baseHandler)
  .use(jsonBodyParser())
  .use(
    validator({
      inputSchema: ajv.compile(inputSchema),
      outputSchema: ajv.compile(outputSchema),
    })
  )
  .use(httpErrorHandler());

export { handler };

We added a new outputSchema, compiled it with Ajv and added it to the Middy validator.

Let’s test our API again with correct schema and Middy validator.

Insomnia request with correct schema

Now the API is back working as expected.

If the schema violates the schema we set in our middleware, the API will throw an error. Let’s quickly try out the case of returning an invalid response.

Instead of returning a number for status code, we’ll return a string instead.

Replace this line:

statusCode: 200,

With this:

statusCode: "success",

Let’s test the API again.

Insomnia request with Middy schema response validation

Great! The server now throws a 500 Internal Server Error to let us know that something is wrong.

Let’s change the status code back.

statusCode: 200,

Deploying to prod

To wrap things up we’ll deploy our app to prod.

$ npx sst deploy --stage prod

This allows us to separate our environments, so when we are working in dev, it doesn’t break the app for our users.

Once deployed, you should see something like this.

 ✅  prod-middy-validator-my-stack


Stack prod-middy-validator-my-stack
  Status: deployed
  Outputs:
    ApiEndpoint: https://bqoc5prkna.execute-api.us-east-1.amazonaws.com

Cleaning up

Finally, you can remove the resources created in this example using the following commands.

$ npx sst remove
$ npx sst remove --stage prod

Conclusion

And that’s it! We’ve got a completely validated serverless API. A local development environment, to test and make changes. And it’s deployed to production as well, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!