Solve - the Rest Api doesn't contain any methods in AWS CDK


Borislav Hadzhiev

Sat May 01 20212 min read


Photo by Joshua Earle

Solving - the Rest Api doesn't contain any methods in 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

The following code adds a GET method to a /tasks resource in Api Gateway and solves the error.

import * as apigateway from '@aws-cdk/aws-apigateway'; import * as lambda from '@aws-cdk/aws-lambda'; import * as cdk from '@aws-cdk/core'; 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 cdk deploy \ --outputs-file ./cdk-outputs.json

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee