goaws-lambdaaws-api-gatewayserverless

Cannot parse API request body in Lambda


I've implemented a Lambda function in Go, where I'm using an API Gateway POST method as the event trigger, configured in my serverless.yml file. However, I'm encountering an issue where the data sent in the API request body is consistently coming through as empty, and I'm unable to parse it. Shall I use other than "APIGatewayProxyRequest"? Despite trying various approaches, the body content is never populated. Any insights on what might be causing this or how to properly handle the request body in this scenario would be greatly appreciated.

Here is a function from my main.go:

func handleRequest(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    log.Printf("Request Body: %v", request.Body)
    var requestBody RequestBody
    if request.Body == "" {
        return events.APIGatewayProxyResponse{
            StatusCode: 400,
            Body:       "Request body is empty",
        }, nil
    }

    err := json.Unmarshal([]byte(request.Body), &requestBody)
    if err != nil {
        log.Printf("Error unmarshalling JSON: %v", err)
        return events.APIGatewayProxyResponse{
            StatusCode: 400,
            Body:       "Invalid JSON input",
        }, nil
    }

    response := events.APIGatewayProxyResponse{
        StatusCode: 200,
        Body:       "Success",
    }

    return response, nil
}

and here is event from my serverless.yml:

    events:
      - http:
          path: /test-method
          method: post
          integration: lambda
          private: true
          request:
            passThrough: NEVER
            template:
              application/json: ${file(templatefile)}```

Solution

  • I fixed the problem with changing the template file, in go APIGatewayProxyRequest is expecting this:

    "Body" : $input.json('$')
    

    But my default template which is taken from api-gateway-mapping-template-reference was using this:

    "body-json" : $input.json('$')
    

    PS: It still does not work if you don't give template property in serverless, therefore it shall be configured