ramsayleung / rspotify

Spotify Web API SDK implemented on Rust
MIT License
632 stars 121 forks source link

Getting bad request error(400) #470

Closed slyeet03 closed 5 months ago

slyeet03 commented 5 months ago

I am trying to fetch user's playlist and store the names in a variable. I get the authorisation url, I do the whole allow access thing then get redirected to a local host. After copying that url and giving it for accessing token, I just get error 400. I have checked my redirect uri and allowed users both are right.

My Code

use futures_util::StreamExt;
use futures_util::TryStreamExt;
use rspotify::{
    clients::OAuthClient, model::SimplifiedPlaylist, scopes, AuthCodeSpotify, ClientCredsSpotify,
    ClientError, Config, Credentials, OAuth,
};
use std::io::{stdin, Read};

use dotenv::dotenv;
use std::env;

async fn fetch_user_playlists() {
    dotenv().ok();

    let client_id = env::var("CLIENT_ID").expect("You've not set the CLIENT_ID");
    let client_secret_id =
        env::var("CLIENT_SECRET_ID").expect("You've not set the CLIENT_SECRET_ID");

    // Using every possible scope
    let scopes = scopes!(
        "user-read-email",
        "user-read-private",
        "user-top-read",
        "user-read-recently-played",
        "user-follow-read",
        "user-library-read",
        "user-read-currently-playing",
        "user-read-playback-state",
        "user-read-playback-position",
        "playlist-read-collaborative",
        "playlist-read-private",
        "user-follow-modify",
        "user-library-modify",
        "user-modify-playback-state",
        "playlist-modify-public",
        "playlist-modify-private",
        "ugc-image-upload"
    );

    let mut oauth = OAuth::default();
    oauth.scopes = scopes;
    oauth.redirect_uri = "http://localhost:8080/callback".to_owned();

    let creds = Credentials::new(&client_id, &client_secret_id);
    let config = Config::default();

    let spotify = AuthCodeSpotify::with_config(creds, oauth, config);

    // Get the URL to request user authorization
    let auth_url = spotify.get_authorize_url(true).unwrap();

    println!("Open this URL in your browser: {}", auth_url);
    println!("After authorizing the application, enter the code:");

    let mut code = String::new();
    stdin().read_line(&mut code).unwrap();

    // Request user token
    let token = spotify.request_token(&code.trim()).await;

    match token {
        Ok(token) => {
            // Get the user's playlists
            let mut playlists = Vec::new();
            let mut stream = spotify.current_user_playlists();

            while let Ok(result) = stream.try_next().await {
                match result {
                    Some(playlist) => playlists.push(playlist),
                    None => break, // End of stream
                }
            }

            // Print the playlists
            for playlist in playlists {
                println!("Playlist: {}", playlist.name);
            }
        }
        Err(err) => {
            println!("Error requesting token: {:#?}", err);
        }
    }
}

pub fn spo() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();

    rt.block_on(fetch_user_playlists());
}

Log/Output data

Error requesting token: Http(
    StatusCode(
        Response {
            url: Url {
                scheme: "https",
                cannot_be_a_base: false,
                username: "",
                password: None,
                host: Some(
                    Domain(
                        "accounts.spotify.com",
                    ),
                ),
                port: None,
                path: "/api/token",
                query: None,
                fragment: None,
            },
            status: 400,
            headers: {
                "date": "Fri, 29 Mar 2024 18:44:59 GMT",
                "content-type": "application/json",
                "content-length": "74",
                "set-cookie": "__Host-device_id=AQCdwurrrrX23aUm8Kdq92i7IaIrTTU5KhbNYPdKZOtW6fWe3LwsSX1x8g5k3-I9PnqMU7Ul4m4FYYc8dp5Qkpy41i2JXYb_Y80;Version=1;Path=/;Max-Age=2147483647;Secure;HttpOnly;SameSite=Lax",
                "set-cookie": "sp_tr=false;Version=1;Domain=accounts.spotify.com;Path=/;Secure;SameSite=Lax",
                "sp-trace-id": "be2db5e1df4a55b1",
                "x-envoy-upstream-service-time": "11",
                "server": "envoy",
                "strict-transport-security": "max-age=31536000",
                "x-content-type-options": "nosniff",
                "vary": "Accept-Encoding",
                "via": "HTTP/2 edgeproxy, 1.1 google",
                "alt-svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000",
            },
        },
    ),
)