DEV Community

Mattia Zanella
Mattia Zanella

Posted on • Edited on

My first lambda function with dev.to API

I'm gonna start this article by mentioning this great article by

So this example will be more or less the same but, instead return a simple Yey! string, we will fetch DEV's API to get my personal data.

DEV's endpoints are listed here.
I'm gonna call my file as DEV_profile.js and inside I'll put this:

const https = require("https");

const options = {
  hostname: 'dev.to',
  path: '/api/users/me',
  headers: { 'api-key': 'YOUR_AMAZING_TOKEN' }
}

const getProfile = (event, context, callback) => {
  // Just a guard to prevent other verbs
  if (event.httpMethod !== 'GET') return

  const req = https.request(options, res => {
    let content = ''
    res.setEncoding("utf8");

    res.on('data', data => (content += data));

    res.on('end',
      body => callback(null, { statusCode: 200, body: content })
    );
  })

  req.on('error', error => console.error(error))
  req.end();
};

module.exports = { handler: getProfile }
Enter fullscreen mode Exit fullscreen mode

Disclaimer: I'm not a backend developer so I'm not sure what I'm doing 🤪 but to handle CORS issues I'm gonna adding some lines to end of the file:

const middy = require('@middy/core')
const cors = require('@middy/http-cors')

/**
 * Let's "middyfy" our handler, then we will be able to attach middlewares to it
 * and Adds CORS headers to responses
 */
const handler = middy(getProfile).use(cors())

module.exports = { handler }
Enter fullscreen mode Exit fullscreen mode

Following this article helped me a lot during development.

Finally you can watch the result here.

That's all 👋 👋

Top comments (0)