Endpoint for file upload (API gateway + Lambda + Python)


#1

Hi,

I’m pretty new to Serverless so please excuse the stupid question. I have a POST endpoint configured with lambda-proxy and working fine with some test data (path variables and query variables are read correctly and so on).

The next step is actually to use the endpoint to upload a file the way my current Flask app works (i.e. with a standard request such as

curl --form "catalogue=@FILE_NAME.zip" ENDPOINT

).
However I cannot seem to find a way to code the endpoint so that you can upload a zip file and save it locally with lambda. In other words, my function below should retrieved the posted data (the zip file) in the event object and save it to the temp folder for further processing (or store it in s3, it’s really the same).

def index(event, context): # read from event the uploaded file and save it as FILE.zip in the temp folder

Can somebody have a detailed explanation or some pointers on how to achieve this?

Thx


Endpoint for file upload (API gateway + Lambda + Python) Serverless Framework
#2

Firstly, you need to (via console only currently) in “Binary Support” add “multipart/form-data”.
This is the Content-Type used by POSTs that include files.

Next, in your code you need to parse the request body itself. Python provides a simple function for this : cgi.parse_multipart

from cgi import parse_header, parse_multipart
from io import BytesIO

def post_file(event, context):

    c_type, c_data = parse_header(event['headers']['Content-Type'])
    assert c_type == 'multipart/form-data'
    form_data = parse_multipart(BytesIO(event['body'].decode('base64')), c_data)

However, it loses the filename along the way.

It’s theoretically possible, in theory, to also use the cgi.FieldStorage, but I haven’t tried yet.


#3

How do you get API gateway to give you the body as base64? For me (python3.6) it’s a utf-8 string.