The Rest Api doesn't contain any methods in AWS CDK


Borislav Hadzhiev

Last updated: Apr 14, 2022


Photo from Unsplash

The Rest Api doesn't contain any methods in AWS CDK #

The reason we get the validation error "The REST API doesn't contain any methods" in AWS CDK is because we are trying to deploy an API Gateway RestApi without setting any resources and methods.

In order to solve the error, we have to define at least 1 resource with a method on the API, i.e. an endpoint /tasks with an HTTP method GET.

The code for this article is available on GitHub

Here's an example that adds a GET method to a /tasks resource in Api Gateway and solves the error.

import * as apigateway from 'aws-cdk-lib/aws-apigateway'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as cdk from 'aws-cdk-lib'; import * as path from 'path'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); const api = new apigateway.RestApi(this, 'api', { deployOptions: {stageName: 'dev'}, }); // 👇 create a lambda function for API integration const getTasksLambda = new lambda.Function(this, 'get-tasks-lambda', { runtime: lambda.Runtime.NODEJS_14_X, handler: 'index.main', code: lambda.Code.fromAsset(path.join(__dirname, '/../src/get-tasks')), }); // 👇 add a /tasks resource const tasks = api.root.addResource('tasks'); // 👇 add a GET method and integrate it with the Lambda function tasks.addMethod('GET', new apigateway.LambdaIntegration(getTasksLambda)); new cdk.CfnOutput(this, 'apiUrl', {value: api.url}); } }

Let's go over what we did in the code snippet.

  1. We created a lambda function, which we will integrate with the API at the /tasks endpoint
  2. We created a /tasks resource
  3. We added a GET http method on the /tasks resource and integrated the method with a Lambda function

The code for the lambda function for the API integration could be as simple as:

async function main(event) { return { body: JSON.stringify([ {taskId: 1, text: 'buy groceries 🛍️'}, {taskId: 2, text: 'wash the dishes 🍽️'}, ]), statusCode: 200, }; } module.exports = {main};

We have now added a /tasks resource with a GET method to our API, which solves the validation error.

The stack can now be deployed with:

npx aws-cdk deploy \ --outputs-file ./cdk-outputs.json

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.