title: API Gateway + Lambda download CSV file
body: <p>I want to do a csv download link with API Gateway + Lambda.
  But there is a problem that lambda always return JSON.stringify. Is there a way to resolve this?</p>
  
  <p>s-function.json</p>
  
  <pre><code>"responses": {
      "default": {
        "statusCode": "200",
        "responseParameters": {
          "method.response.header.Content-disposition": "'attachment; filename=testing.csv'"
        },
        "responseTemplates": {
          "text/csv": ""
        }
      }
    }
  </code></pre>
  
  <p>handler.js</p>
  
  <pre><code>var json2csv = require('json2csv');
  module.exports.handler = function(event, context, cb) {
     var fields = ['car', 'price', 'color'];
     var myCars = [
      {
        "car": "Audi",
        "price": 40000,
        "color": "blue"
      }, {
        "car": "BMW",
        "price": 35000,
        "color": "black"
      }, {
        "car": "Porsche",
        "price": 60000,
        "color": "green"
      }
     ]; 
      var csv = json2csv({ data: myCars, fields: fields });
      return cb(null, csv);
  };
  </code></pre>
  
  <p>In the downloaded csv file.</p>
  
  <blockquote>
    <p>"\"car\",\"price\",\"color\"\n\"Audi\",40000,\"blue\"\n\"BMW\",35000,\"black\"\n\"Porsche\",60000,\"green\""</p>
  </blockquote>
  
  <p>Updated:</p>
  
  <p>I still trying but thank you at least I have direction.
  By the way, I can't find API Gateway doc about $input.body.replaceAll. replaceAll is Java function?</p>
  
  <p>Finally, I resolve this by below code in Api Gateway template.</p>
  
  <pre><code>$input.body.replaceAll("\\""","").replaceAll("""","").replaceAll("\\n","
  ")
  </code></pre>
  
  <p>s-function escaped double quotes.</p>
  
  <pre><code>"responseTemplates": {
      "text/csv": "$input.body.replaceAll(\"\\\\\"\"\",\"\").replaceAll(\"\"\"\",\"\").replaceAll(\"\\\\n\",\"\n\")"
  }
  </code></pre>
  
  <p>return data:</p>
  
  <pre><code>car,price,color
  Audi,40000,blue
  BMW,35000,black
  Porsche,60000,green
  </code></pre>
  
  <p>The template final replaceAll is weird. CSV don't recognize \n or \r\n, but I try copy new line in IDE and pass to code. It work and it's magical.</p>