Created
February 7, 2014 14:00
-
-
Save LnL7/8863068 to your computer and use it in GitHub Desktop.
Fetching JSON using http-conduit and aeson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
import Control.Applicative (Applicative, (<$>), (<*>)) | |
import Control.Monad (mzero) | |
import Data.Aeson (Value(..), FromJSON, (.:), parseJSON) | |
import Data.ByteString (ByteString) | |
import Data.Text (Text) | |
import Network.HTTP.Conduit (Response) | |
import qualified Data.Aeson as A | |
import qualified Data.Aeson.Parser as AP | |
import qualified Data.ByteString as B | |
import qualified Data.ByteString.Lazy as BL | |
import qualified Network.HTTP.Conduit as HC | |
import qualified System.Environment as E | |
data TVShow = TVShow | |
{ ident :: Int | |
, name :: !Text | |
, overview :: !Text | |
} | |
deriving (Show) | |
instance FromJSON TVShow where | |
parseJSON (Object v) = TVShow | |
<$> v .: "id" | |
<*> v .: "name" | |
<*> v .: "overview" | |
parseJSON _ = mzero | |
fetchJson :: String -> IO (Response BL.ByteString) | |
fetchJson url = do | |
req <- HC.parseUrl url | |
HC.withManager $ \manager -> do | |
HC.httpLbs req manager | |
main :: IO () | |
main = do | |
key <- E.getEnv "API_KEY" | |
res <- fetchJson (url ++ key) | |
let | |
mtv :: Maybe TVShow | |
mtv = A.decode lbs | |
lbs = HC.responseBody res | |
print $ HC.responseStatus res | |
case mtv of | |
Just tv -> print tv | |
Nothing -> return () | |
where | |
url :: String | |
url = "https://api.themoviedb.org/3/tv/1705?api_key=" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment