Skip to content

Instantly share code, notes, and snippets.

@SadPandaBear
Last active May 20, 2018 22:39
Show Gist options
  • Save SadPandaBear/8cc011eb61e2b185350d076d1f66acd6 to your computer and use it in GitHub Desktop.
Save SadPandaBear/8cc011eb61e2b185350d076d1f66acd6 to your computer and use it in GitHub Desktop.
Spotify Client Credentials Flow with Haskell
{-# LANGUAGE OverloadedStrings #-}
module Lib
( someFunc
) where
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import qualified Data.ByteString.Char8 as B8 (pack)
import qualified Data.ByteString.Lazy.Char8 as L8
import System.Environment (lookupEnv)
import Data.Aeson
import Text
data Auth = Auth {token :: Text} deriving (Show)
instance FromJSON Auth where
parseJSON = withObject "auth" $ \o ->
Auth <$> o .: "access_token"
instance ToJSON Auth where
toJSON a = object ["access_token" .= token a]
someFunc :: IO ()
someFunc = do
putStrLn "Search for an artist on Spotify."
line <- getLine
runSpotify
runSpotify :: IO ()
runSpotify = do
secret <- lookupEnv "SPOTIFY_SECRET"
case secret of
Just s -> do
auth <- authenticate s
case auth of
Just a -> putStrLn $ show a
Nothing -> putStrLn "No records"
Nothing -> putStrLn "SPOTIFY_SECRET couldn't be retrieved from environmental variables."
authenticate :: String -> IO (Maybe Auth)
authenticate s = do
manager <- newManager tlsManagerSettings
initReq <- parseRequest "https://accounts.spotify.com/api/token"
let requestObject = [("grant_type", "client_credentials")]
let req = urlEncodedBody requestObject initReq
{ method = "POST"
, requestHeaders =
[ ("Authorization", B8.pack s)
, ("Content-Type", "application/x-www-form-urlencoded")
]
}
response <- httpLbs req manager
return $ decode $ responseBody response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment