Getting grant_type error when authenticating with Spotify Web API

I’m trying to authenticate with the Spotify Web API using client credentials but keep running into an issue. Every time I make the request, I get a 400 error saying the grant_type is unsupported even though I’m setting it correctly.

The error message I’m getting is:

400 Bad Request: {"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}

Here’s my authentication function:

sub fetch_auth_token {
    my $params = {grant_type => "client_credentials"};
    
    my $request = HTTP::Request->new("POST", TOKEN_ENDPOINT, [
        "Content-Type" => "application/x-www-form-urlencoded", 
        "Authorization" => "Basic $ENV{SPOTIFY_AUTH_B64}",
    ], encode_utf8 encode_json $params);
    
    my $response = $ua->request($request);
    
    if ($response->is_success) {
        return %{decode_json $response->content}{"access_token"};
    } else {
        die $response->status_line . ": " . $response->content . "\n";
    }
}

What could be causing this grant_type validation to fail?

found ur problem - you’re sending json data but telling spotify it’s form-encoded. spotify wants form data, not json for token requests. use uri::escape and send ur params as a “grant_type=client_credentials” string instead of json encoding.

Your Content-Type header doesn’t match what you’re actually sending. You’re saying it’s application/x-www-form-urlencoded but then you’re encoding the parameters as JSON in the body. Spotify’s token endpoint wants real form-encoded data when you use that content type. I hit this same issue when I started with their API. Just swap out your encode_utf8 encode_json $params with "grant_type=client_credentials" as the request body. You could also use URI::Escape to handle the encoding, but for something this simple with just grant_type, a hardcoded string works fine. Bottom line: your request body format has to match your Content-Type header.

Had this exact problem a few months ago. Your header says application/x-www-form-urlencoded but you’re sending JSON. The server expects form data like grant_type=client_credentials, not JSON structure. Spotify’s API is strict - it parses based on your Content-Type header. When it tries to read your JSON as form data, it can’t find the grant_type parameter. That’s why you get unsupported grant_type instead of a parsing error. Replace that encode_json line with a plain string. Spent way too much time debugging this myself.

classic mismatch - ur sending json but header says it’s form data. spotify checks content-type first, then tries to parse based on that. it can’t find grant_type bcuz it’s expecting form encoding. just change that last line to send a raw string instead of json.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.