Open2

AWS Lambdaから外部ライブラリに依存せずにHTTPリクエストする

lsiilsii

Pythonの場合

from urllib import request

def lambda_handler(event, context):
    url = 'https://example.com'
    res = req(url)
    return {
        'url': url,
        'res': res,
    }

def req(url):
    get_req = request.Request(url)
    with request.urlopen(get_req) as res:
        body = res.read()
        return body

lsiilsii

Node.jsの場合

const https = require('https')

exports.handler = async (event) => {
    const url = 'https://example.com'
    
    const res = await req(url)
        .catch(err => err)
    
    return {
        url,
        res
    }
}

async function req (url) {
    return new Promise((resolve, reject) => {
        https.get(url, (resp) => {
            let data = ''
            resp.on('data', (chunk) => {
                data += chunk
            })
            resp.on('end', () => {
                resolve(data)
            })
        })
        .on('error', (err) => {
          reject(err)
        })
    })
}