Lamba Function Spotify API

Howdy yall,

Just tryna work some Lamba function and wondering if someone has some input they could help me out with because I think I am missing something small.

I want to authorize a user and access their Spotify data with Spotfiy’s API.

const axios = require("axios")
const qs = require("qs")

exports.handler = async function(event, context) {
  // apply our function to the queryStringParameters and assign it to a variable
  const API_PARAMS = qs.stringify(event.queryStringParameters)
  // Get env var values defined in our Netlify site UI
  // TODO: change this
  const API_SECRET = "XXXXX";
  var REDIRECT_URI = 'http://localhost:8888/app/profile/';

  // TODO: customize your URL
  // this is secret too, your frontend won't see this
  const URL = `https://accounts.spotify.com/authorize?client_id=${API_SECRET}&response_type=code&redirect_uri=${REDIRECT_URI }&scope=user-read-private%20user-read-email&state=34fFs29kd09`;


  console.log("Constructed URL is ...", URL)

  try {
    const { data } = await axios.get(URL)
    // refer to axios docs for other methods if you need them
    // for example if you want to POST data:
    //    axios.post('/user', { firstName: 'Fred' })
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    }
  } catch (error) {
    const { status, statusText, headers, data } = error.response
    return {
      statusCode: error.response.status,
      body: JSON.stringify({ status, statusText, headers, data }),
    }
  }
}

But this only gets the HTML for the site that would ask the user for authorization, how would I open it in a new tab and then get the response token back using Lambda functions. I think I just don’t understand Lamba and if someone could explain I would be in a lot better position to succeed.

I did check out https://github.com/DavidWells/netlify-functions-workshop and that helped but I still think I am missing something.

I also tried to read https://gist.github.com/amjohnson38/7c9f206060f47e78e568bf47453aaeb6 but it just didn’t make sense to me and I want to understand how I can do this not just copy code

Hey @ethaneisenhard!

I haven’t worked with the Spotify API but I’ve done very similar oauth flows with serverless functions before that may be able to help. There is some redirect magic happening with making sure a user authenticates with Google/Spotify/etc and retrieving an access token that you can then use to pull data from their account. You essentially have to have 2 functions, one that generates a URL to send users to authenticate with and another that will create the access token you need to access the API. Hopefully this post sheds light on that process:

https://dev.to/shortdiv/take-charge-of-your-meeting-schedule-with-the-google-calendar-api-and-netlify-functions-1dhp

Let me know if you have any questions, and I’ll do my best to address them!