kochizufan
kochizufan

Reputation: 2441

How can I pass binary content to API Gateway from node JS AWS lambda backend using Serverless framework?

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

Environment:

With above environments, in my code I have response content as Binary (Buffer objects array).
But, if I give Buffer objects array as response directly,

callback(null,{
    headers: {'Content-Type': 'image/jpeg'},
    body: body
});

Receiving 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 response by base64 encoded,

callback(null,{
    headers: {'Content-Type': 'image/jpeg'},
    body: body.toString('base64')
});

Receiving response is like this:

Content-type: image/jpeg
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA...

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

== PostScript ==

According to this document:
AWS API Gateway Binary output without Accept header
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?

== Edited Jan. 17th ==

Hi @ka-hou-ieong

You wrote rest-api-id and resource-id, they are in below images, right?

enter image description here

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)

Upvotes: 12

Views: 3119

Answers (1)

Ka Hou Ieong
Ka Hou Ieong

Reputation: 6510

If you want to force the response as a binary response, you can set 'CONVERT_TO_BINARY' to the contentHandling on integration response via AWS CLI or via API. Currently, we are lack of this option on the console.

API

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

{
    "patchOperations" : [ {
        "op" : "replace",
        "path" : "/contentEncoding",
        "value" : "CONVERT_TO_BINARY"
  }]
}

CLI

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

Upvotes: 3

Related Questions