計算機科学のブログ

実践Haskell HTTPリクエストの作成 getResponseStatus関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON39(HaskellでのHTTPリクエストの作成)、39.6(練習問題)Q39-2の解答を求めてみる。

コード

Main.hs

module Main where

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC
import Network.HTTP.Simple

myToken :: BC.ByteString
myToken = "<API トークン>"

noaaHost :: BC.ByteString
noaaHost = "www.ncdc.noaa.gov"

apiPath :: BC.ByteString
apiPath = "/cdo-Web/api/v2/datasets"

response :: IO (Response LC.ByteString)
response = httpLBS "http://news.ycombinator.com"

buildRequest :: p -> BC.ByteString -> BC.ByteString -> BC.ByteString -> Request
buildRequest token host method path =
  setRequestMethod method $
    setRequestHost host $
      setRequestHeader "token" [myToken] $
        setRequestPath path $
          setRequestSecure True $
            setRequestPort 443 defaultRequest

request :: Request
request = buildRequest myToken noaaHost "GET" apiPath

main :: IO ()
main = do
  response <- httpLBS request
  let status = getResponseStatusCode response
  if status == 200
    then do
      print "saving request to file"
      let jsonBody = getResponseBody response
      L.writeFile "data.json" jsonBody
    else print $ getResponseStatus response

入出力結果(Terminal, Zsh)

% stack build
http-lesson> build (lib + exe)
Preprocessing library for http-lesson-0.1.0.0..
Building library for http-lesson-0.1.0.0..
Preprocessing executable 'http-lesson-exe' for http-lesson-0.1.0.0..
Building executable 'http-lesson-exe' for http-lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/http-lesson-exe/http-lesson-exe ...
http-lesson> copy/register
Installing library in /Users/…/http-lesson/.stack-work/install/x86_64-osx/e8aa255f05230c729a6925540310c5d25fa2ee7edb295ecd65b1d55a14d8280b/9.0.2/lib/x86_64-osx-ghc-9.0.2/http-lesson-0.1.0.0-7VoYrQcVxswJmRwg5jgroZ
Installing executable http-lesson-exe in /Users/…/http-lesson/.stack-work/install/x86_64-osx/e8aa255f05230c729a6925540310c5d25fa2ee7edb295ecd65b1d55a14d8280b/9.0.2/bin
Registering library for http-lesson-0.1.0.0..
% stack exec http-lesson-exe
Status {statusCode = 404, statusMessage = "Not Found"}
%