#help
1 messages · Page 1 of 1 (latest)
Your code is a Next.js API route that fetches an access token from Spotify's API and then uses that token to fetch a playlist. If successful, it returns two random tracks from that playlist. If there's an error at any point, it returns a 500 status with the error message.
Here's a breakdown of what your code does:
-
It imports the necessary types and libraries.
NextApiRequestandNextApiResponseare types from Next.js used for typing the request and response in your API route.axiosis a promise-based HTTP client for making requests. -
The
getSpotifyAccessTokenfunction makes a POST request to Spotify's token endpoint to get an access token. It sends the client ID and client secret as part of the Authorization header. -
The default exported function
handleris your API route. It's an async function that takes a request and a response. -
Inside
handler, it first callsgetSpotifyAccessTokento get an access token. -
It then makes a GET request to a Spotify playlist endpoint, passing the access token in the Authorization header.
-
It gets the tracks from the response, picks two at random, and sends them back in the response with a 200 status.
-
If there's an error at any point, it catches it and sends a 500 status with the error message.
Remember to validate and handle the data you receive from the Spotify API appropriately. The body of NextApiRequest is any because the client may include any payload. You should validate the type/shape of the body at runtime before using it (source (https://nextjs.org/docs/pages/building-your-application/routing/api-routes#adding-typescript-types)).
Also, ensure that your environment variables (process.env.SPOTIFY_CLIENT_ID and process.env.SPOTIFY_CLIENT_SECRET) are correctly set up in your Next.js application.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@magic bobcat kapa.ai is still learning and improving, please let us know how it did by reacting below
import type { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";
async function getSpotifyAccessToken() {
const response = await axios.post(
"https://accounts.spotify.com/api/token",
null,
{
params: {
grant_type: "client_credentials",
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${Buffer.from(
`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}`
).toString("base64")}`,
},
}
);
return response.data.access_token;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const accessToken = await getSpotifyAccessToken();
console.log({ accessToken });
const response = await axios.get(
`https://open.spotify.com/playlist/6E34Ag3EQHCOdjY10gFogj?si=5822e634bf0845a1/`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const tracks = response.data.items;
const randomTracks = tracks.sort(() => 0.5 - Math.random()).slice(0, 2);
res.status(200).json(randomTracks);
} catch (error: any) {
res.status(500).json({ error: error.message });
}
}
GET http://localhost:3000/api/spotify 404 (Not Found)
Can you fix my code? @latent spear
Let me check the knowledge base for you. One moment! :books:
Based on the information provided, it seems like your Next.js server is not able to find the route /api/spotify. Here are a few things you can check:
-
File Location: Make sure your file is located in the correct directory. In Next.js, API routes should be inside the
pages/apidirectory. So, if you want to create a/api/spotifyroute, your file structure should look like this:pages/api/spotify.ts. -
File Name: Ensure that your file is named correctly. If you're using TypeScript, your file should have a
.tsextension (e.g.,spotify.ts). -
Server Running: Make sure your Next.js server is running. You can start it with
npm run devoryarn dev. -
Correct Export: Ensure that you're exporting your API route handler correctly. It should be a default export. From your code, it seems like you're doing this correctly.
If you've checked all of these and you're still having issues, there might be a problem elsewhere in your application. Unfortunately, without more information, it's hard to provide a more specific solution.