Skip to content

Instantly share code, notes, and snippets.

@fujimura fujimura/api.hs
Last active Dec 16, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

fujimura commented Apr 15, 2013

$ 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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.