title: How to make lambda function return a json containing an image in python
body: <p>I'm building a web application that send some information to an API (API Gateway of AWS) and it receive back an image and some informations (strings) about that image. The strings and the image are generated by a lambda function (AWS service) written in <strong>python</strong>.</p>
  <p>Reading <a href="https://stackoverflow.com/questions/63565132/file-object-image-as-value-in-a-dictionary-python">this</a> I converted my image into Base64 encoding using base64 library and send it as a part of my json response, but i get <code>Object of type bytes is not JSON serializable</code>, how can i solve this?</p>
  <p>The answer to this <a href="https://stackoverflow.com/questions/37464600/send-mysql-blob-content-as-a-json-response">question</a> shows code that does the same thing my code does, but in the comments of that answer it says that code works, while mine doesn't, am I doing something wrong?</p>
  <p>This is my code:</p>
  <pre><code>def f():
      ...
      bio = BytesIO()
      plt.savefig(bio, format=&quot;png&quot;)
  
      bio.seek(0)
      my_base64_jpgData = base64.b64encode(bio.read())
      result[&quot;image&quot;] = my_base64_jpgData
      return result
  
  def lambda_handler(event, context):
      body = event[&quot;body&quot;]
  
      result = handler(body)
  
      return {
          'statusCode': 200,
          'body': json.dumps(result)
      }
  </code></pre>
  <p>If I test this locally i can avoid doing <code>json.dumps()</code> and return only <code>result</code>, but trying the same code in a lambda function make it fails because (i think) the lambda function before sending the response apply json.dumps to it.</p>
  <p>EDIT:
  Also the answer to <a href="https://stackoverflow.com/questions/42548675/python-send-file-through-json">this question</a> says to do what I did (use base64) but I don't understand why it doesn't work for me</p>