Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

As we know, API Gateway and lambda support binary request/response, but I have one question for backend programming in node JavaScript. 

Environment:

  • Using the Serverless framework, with lambda (not lambda-proxy) integration.
  • Response header mapping is:
  • Content-Type: integration.response.body.headers.Content-Type
  • Response template mappings are: 
    • image/png: $input.path('$.body') 
    • image/jpeg: $input.path('$.body')
  • Enable Binary Support for image/png and image/jpeg

With the above environments, in my code, I have response content as Binary (Buffer objects array).

But, if I give Buffer objects array as a response directly, 

callback(null,{

    headers: {'Content-Type': 'image/jpeg'},

    body: body

});

Receiving a response is like this: 

Content-type: image/jpeg

{type=Buffer, data=[255,216,255,224,0,16,74,70,73,70,0...

If I give Buffer objects array as a response by base64 encoded, 

callback(null,{

    headers: {'Content-Type': 'image/jpeg'},

    body: body.toString('base64')

});

Receiving a response is like this: 

Content-type: image/jpeg

/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA...

How can I give a binary response to API Gateway from node JS backend using Serverless framework?

According to this document:

We must set "Content Handling" of Integration response change to "CONVERT TO BINARY", for responding binary response.

But how can I set this?

I have no idea both from serverless.yml and AWS console GUI. 

And if I successfully set this Content Handling => CONVERT TO BINARY, might I solve responding binary response?

But using these ids, command result said: 

$aws apigateway put-integration-response --rest-api-id XXXXXXXX --resource-id XXXXXX --http-method GET --status-code 200 --content-handling CONVERT_TO_BINARY

An error occurred (NotFoundException) when calling the PutIntegrationResponse operation: Invalid Resource identifier specified

What wrong with this? I use latest aws-cli (aws-cli/1.11.37 Python/2.7.9 Darwin/16.3.0 botocore/1.5.0)

1 Answer

0 votes
by (44.4k points)

If you want a binary response, then you will have to set ‘CONVERT_TO_BINARY’ to contentHandling on integration.

CLI

aws apigateway put-integration-response --rest-api-id xxxxxxx --resource-id xxxxx --http-method GET --status-code 200 --content-handling CONVERT_TO_BINARY 

API

PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration/responses/<status_code>

 

{

    "patchOperations" : [ {

        "op" : "replace",

        "path" : "/contentEncoding",

        "value" : "CONVERT_TO_BINARY"

  }]

}

Browse Categories

...