DEV Community

Mattia Zanella
Mattia Zanella

Posted on • Edited on

2 1

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 👋 👋

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay