Skip to content

Instantly share code, notes, and snippets.

@fujimura
Last active December 16, 2015 05:59
Show Gist options
  • Save fujimura/5388019 to your computer and use it in GitHub Desktop.
Save fujimura/5388019 to your computer and use it in GitHub Desktop.
Hit an web API with http-streams and aeson
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Data.Aeson (FromJSON, parseJSON, (.:))
import qualified Data.Aeson as AE
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Network.Http.Client (Response, concatHandler, get)
import OpenSSL (withOpenSSL)
import System.IO.Streams (InputStream, toList)
data User = User
{ userId :: String
, userName :: String
} deriving Show
instance FromJSON User where
parseJSON (AE.Object v) = User <$>
v .: "id" <*>
v .: "name"
parseJSON _ = mzero
jsonHandler :: FromJSON a => Response -> InputStream ByteString -> IO (Maybe a)
jsonHandler r i = (AE.decode . LBS.fromChunks) <$> toList i
main :: IO ()
main = withOpenSSL $ do
user <- get "http://graph.facebook.com/dfujimura" jsonHandler :: IO (Maybe User)
print user
@fujimura
Copy link
Author

$ ghc --make -threaded api.hs
[1 of 1] Compiling Main             ( api.hs, api.o )
Linking api ...
$ ./api
Just (User {userId = "100001730250658", userName = "\34276\26449 \22823\20171"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment