Skip to content

Instantly share code, notes, and snippets.

@bitmvr
Last active December 18, 2023 17:45
Show Gist options
  • Save bitmvr/c13256200f5d582131720e2548f30e88 to your computer and use it in GitHub Desktop.
Save bitmvr/c13256200f5d582131720e2548f30e88 to your computer and use it in GitHub Desktop.
Spotify API Example | Get Artist
#!/usr/bin/env bash
# Learn More About Spotify API
# https://developer.spotify.com/documentation/web-api/tutorials/getting-started
if [ -z "${SPOTIFY_CLIENT_ID}" ] || [ -z "${SPOTIFY_CLIENT_SECRET}" ]; then
echo "SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET must be set."
exit 1
fi
for cmd in curl jq; do
if ! command -v $cmd &> /dev/null; then
echo "Command $cmd could not be found"
exit 1
fi
done
SPOTIFY_ACCESS_TOKEN_FILE='spotify.token'
__request_spotify_access_token(){
token_url='https://accounts.spotify.com/api/token'
data="$(curl -X POST "${token_url}" \
--silent \
--header "Content-Type: application/x-www-form-urlencoded" \
--data "grant_type=client_credentials" \
--data "client_id=${SPOTIFY_CLIENT_ID}" \
--data "client_secret=${SPOTIFY_CLIENT_SECRET}" \
)"
echo "$data" > "$SPOTIFY_ACCESS_TOKEN_FILE"
}
__read_spotify_access_token(){
jq --raw-output .access_token "$SPOTIFY_ACCESS_TOKEN_FILE"
}
__has_error(){
echo "$1" | jq --exit-status '.error' > /dev/null 2>&1
}
__print_error(){
echo "$1" | jq --raw-output '.error.message'
}
__confirm_response(){
response="$1"
if __has_error "$response"; then
__print_error "$response"
exit 1
fi
}
__request_artist_data(){
access_token="$1"
artist_id="$2"
response="$(curl "https://api.spotify.com/v1/artists/${artist_id}" \
--silent \
--header "Authorization: Bearer ${access_token}" \
)"
__confirm_response "$response" && echo "$response"
}
__request_spotify_access_token
access_token="$(__read_spotify_access_token)"
artist_id='4Z8W4fKeB5YxbusRsdQVPb'
__request_artist_data "$access_token" "$artist_id"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment