Skip to content

0.5.7

Compare
Choose a tag to compare
@mnapoli mnapoli released this 27 Sep 07:49
· 2488 commits to master since this release

By default API Gateway does not support binary HTTP responses like images, PDF, binary files… To achieve this, you need to enable the option for binary responses in serverless.yml:

provider:
    # ...
    apiGateway:
        binaryMediaTypes:
            - '*/*'

This will make API Gateway support binary responses for all responses. Your application can now return binary responses as usual.

However, you must define a Content-Type header on binary responses. If you don't, you may get the following error: Failed encoding Lambda JSON response: Malformed UTF-8 characters, possibly incorrectly encoded. Symfony's helpers or Laravel's helpers will take care of that for you. If you don't use them, here are some examples:

// Vanilla PHP example with a JPEG image response:
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($filename));
fpassthru(fopen($filename, 'rb'));

// PSR-7 example:
return $response
    ->withHeader('Content-Type', 'image/jpeg')
    ->withHeader('Content-Length', (string) filesize($filename))
    ->withBody(new Stream($filename));