Skip to content

Commit

Permalink
Add OpenWeatherMap api
Browse files Browse the repository at this point in the history
  • Loading branch information
jorpic committed Oct 1, 2017
1 parent 1d4c9d3 commit 6256f39
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
71 changes: 71 additions & 0 deletions WeatherApi/OpenWeatherMap.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{-# LANGUAGE OverloadedStrings #-}
module WeatherApi.OpenWeatherMap (initApi) where

import Network.HTTP
import Network.URI
import WeatherApi hiding (humidity)
import Codec.Binary.UTF8.String (encodeString)
import Data.ByteString.Char8 (pack, unpack)
import Data.Aeson
import Data.Aeson.TH
import Data.Attoparsec.ByteString hiding (Result(..))
import Data.Maybe

import Control.Applicative
import qualified Data.Vector as V

import WeatherApi.Util

apiUrl = "http://api.openweathermap.org/data/2.5/weather?"

type ApiKey = String

instance FromJSON Weather where
parseJSON (Object o) = do
Object m <- o .: "main"
Weather
<$> pure 0.0
<*> (m .: "temp")
<*> pure ""
<*> pure ""
<*> pure ""

-- | Make config for use with WeatherApi functions
initApi :: ApiKey -> Config
initApi key =
let params = [("units", "metric"), ("appid", key)]
urn c = urlEncodeVars $ params ++ [("q", encodeString c)]
in Config { apiHost = "api.openweathermap.org"
, apiPort = 80
, queryFun = makeQueryFun urn
}

retrieve s urn =
case parseURI $ apiUrl ++ urn of
Nothing -> return $ Left $ NetworkError "Invalid URL"
Just uri -> get s uri

get s uri = do
eresp <- sendHTTP s (Request uri GET [] "")
case eresp of
Left err -> return $ Left $ NetworkError $ show err
Right res -> return $ Right $ rspBody res

-- | This return function witch will actualy retrieve and parse weather from stream
makeQueryFun :: (String -> String)
-> (HandleStream String)
-> String
-> IO ApiResponse
makeQueryFun q stream city =
do
resp <- retrieve stream $ q city
case resp of
Left err -> return $ Left err
Right c -> do
case maybeResult $ parse json $ pack c of
Nothing -> return $ Left $ ParseError "Bad response"
Just v ->
return $ case fromJSON v :: Result Weather of
Error e -> Left $ ParseError $ "Can't parse data: " ++ e
Success v -> Right v

3 changes: 2 additions & 1 deletion package.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: weather-api
version: "0.4.3.3"
version: "0.4.4"
synopsis: Weather API implemented in Haskell
description: This library implement generic API for retrieving weather
by HTTP, and has Google weather API as example.
Expand All @@ -14,6 +14,7 @@ library:
exposed-modules:
- WeatherApi
- WeatherApi.WWOnline
- WeatherApi.OpenWeatherMap
other-modules:
- WeatherApi.Util
dependencies:
Expand Down

0 comments on commit 6256f39

Please sign in to comment.