modular api handling part 1
This commit is contained in:
parent
6eb0be23a2
commit
c4eb5ab8ae
@ -7,6 +7,7 @@ to get the needed dependencies.
|
|||||||
|
|
||||||
### Dependencies
|
### Dependencies
|
||||||
This project makes use of the following dependencies (specified in `profun.cabal`):
|
This project makes use of the following dependencies (specified in `profun.cabal`):
|
||||||
* http-client
|
* http-client (for API requests)
|
||||||
* http-client-tls
|
* http-client-tls (for API requests)
|
||||||
* http-conduit
|
* http-conduit (for API requests)
|
||||||
|
* aeson (JSON parsing)
|
32
app/Main.hs
32
app/Main.hs
@ -1,8 +1,34 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-} --needed for string arguments
|
{-# LANGUAGE OverloadedStrings #-} --needed for ByteString arguments
|
||||||
import Network.HTTP.Simple
|
import Network.HTTP.Simple
|
||||||
|
import System.Environment (lookupEnv)
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = do
|
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)
|
|
||||||
|
|
||||||
|
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"
|
||||||
|
@ -67,7 +67,8 @@ executable profun
|
|||||||
build-depends: base ^>=4.17.2.1,
|
build-depends: base ^>=4.17.2.1,
|
||||||
http-client ^>=0.7.17,
|
http-client ^>=0.7.17,
|
||||||
http-client-tls ^>=0.3.6.3,
|
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.
|
-- Directories containing source files.
|
||||||
hs-source-dirs: app
|
hs-source-dirs: app
|
||||||
|
Loading…
Reference in New Issue
Block a user