Edmund Sulzanok
Edmund Sulzanok

Reputation: 1973

Spotify Malformed Json

https://api.spotify.com/v1/me/player/play endpoint keeps throwing an error

Client error: PUT https://api.spotify.com/v1/me/player/play?device_id=b3be3728123923782d72b3c0b5e7e3d91b9dfb10 resulted in a 400 Bad Request response: { "error" : { "status" : 400, "message" : "Malformed json" } }`

Here's my code:

$client = new GuzzleHttp\Client();
$res = $client->request('PUT', 'https://api.spotify.com/v1/me/player/play?device_id=".$request->device_id', [
    "headers" => [
        "Authorization" =>  ["Bearer " . $session_owner->spotify_token],
        "Content-Type" => "application/x-www-form-urlencoded",
    ],
    "form_params" => [
        "uris" => ["spotify:track:" . $request->spotify_song_id]
    ]
]);

So far this is the only endpoint that gives me this problem. If I comment out context_uri line, then the playback of the last track on last active device starts properly.

Here's what that line translate to:

"form_params": {
    "uris": ["spotify:track:2Hy7ypRUKL4OPqtNlzBHWM"]
}

Upvotes: 2

Views: 411

Answers (1)

MrCode
MrCode

Reputation: 64536

Spotify requires the request body to be a JSON string but you are sending URL encoded form data.

Change the content type to application/json and form_params to json:

"headers" => [
    "Authorization" =>  ["Bearer " . $session_owner->spotify_token],
    "Content-Type" => "application/json",
],
"json" => [
    "context_uri" => "spotify:track:" . $request->spotify_song_id,
]

Guzzle will now send the JSON as the complete request body with no form params.

Upvotes: 1

Related Questions