From c4eb5ab8aeddd755b69504a076ce6ae8b931653d Mon Sep 17 00:00:00 2001 From: Szymon Szczubkowski Date: Sat, 25 May 2024 20:21:38 +0200 Subject: [PATCH] modular api handling part 1 --- README.md | 7 ++++--- app/Main.hs | 32 +++++++++++++++++++++++++++++--- profun.cabal | 3 ++- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d4c7d0f..f6b19e2 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ to get the needed dependencies. ### Dependencies This project makes use of the following dependencies (specified in `profun.cabal`): -* http-client -* http-client-tls -* http-conduit \ No newline at end of file +* http-client (for API requests) +* http-client-tls (for API requests) +* http-conduit (for API requests) +* aeson (JSON parsing) \ No newline at end of file diff --git a/app/Main.hs b/app/Main.hs index 4f66864..4a68e3c 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -1,8 +1,34 @@ -{-# LANGUAGE OverloadedStrings #-} --needed for string arguments +{-# LANGUAGE OverloadedStrings #-} --needed for ByteString arguments import Network.HTTP.Simple +import System.Environment (lookupEnv) main :: IO () main = do - apiResponse <- httpLBS "POST http://httpbin.org/get" + apiKey <- getWeatherKey + let todayRequest = apiRequestBuilder apiKey "today" + response <- httpJSON todayRequest :: IO (Response ()) + putStrLn $ show todayRequest + putStrLn $ show $ getResponseStatusCode response + --apiResponse <- httpJSON "http://httpbin.org/get" :: IO (Response ()) -- specifying type as httpJSON return value is ambigious - putStrLn $ "Status code: " ++ show (getResponseStatusCode apiResponse) \ No newline at end of file + + +getWeatherKey :: IO String +getWeatherKey = do + result <- lookupEnv "WEATHER_API_KEY" + case result of + Just a -> return a + Nothing -> error "API key not set in environmental variables!" -- exception thrown (but not handled) per project requirement + +apiRequestBuilder :: String -> String -> Request +apiRequestBuilder apiKey day = + setRequestHost "api.weatherapi.com" + $ setRequestPath path + $ setRequestMethod "GET" + $ setRequestQueryString [("q", Just "Poznan"), ("key", Just "apiKey")] + $ setRequestPort 443 + $ setRequestSecure True + $ defaultRequest + where path + | day == "today" = "/v1/current.json" + | otherwise = "/d" diff --git a/profun.cabal b/profun.cabal index 60c2f15..551f973 100644 --- a/profun.cabal +++ b/profun.cabal @@ -67,7 +67,8 @@ executable profun build-depends: base ^>=4.17.2.1, http-client ^>=0.7.17, http-client-tls ^>=0.3.6.3, - http-conduit ^>=2.3.8.3 + http-conduit ^>=2.3.8.3, + aeson ^>=2.2.2.0 -- Directories containing source files. hs-source-dirs: app