Search code examples
jsonhaskellghciaeson

Exception: JSONError "content type of response is \"application/random.v4+json\"" #Haskell


I am using Network.Wreq, Control.Lens, Data.Aeson

getInfo = do
    let opts = defaults && header "Accept" .~ ["application/random.v4+json"] "Content-Type" .~ ["application/json"]
    resp <- asJSON =<< getWith opts "url" :: IO (Response (Map String Value))
    let respBody = resp ^. responseBody
    return respBody

response has Content-Type → application/random.v4+json

when I call the function it throws an exception saying

Exception: JSONError "content type of response is \"application/random.v4+json\""

But when I make a call to an API whose response has simple Content-Type → application/json instead of having some fancy Content-Type → application/random.v4+json

my function works all expected. When the response contenty-type changes to anything otherthan application/json it throws me the above error.

Why is it throwing an exception ? How can make it to work for all the versions of my API ?

**Note: Both versions of API returns same kind of data.


Solution

  • Network.Wreq.asJSON will throw a JSONError if response's content type is different from "application/json".

    I guess the easiest way to go would be to explicitly use Aeson to decode the response body as json:

    getInfo = do
        let opts = defaults && header "Accept" .~ ["application/random.v4+json"] "Content-Type" .~ ["application/json"]
        resp <- getWith opts "url"
        let respBody = decodeResponseBody $ resp ^. responseBody
        return respBody
      where
        decodeResponseBody :: ByteString -> Map String Value
        decodeResponseBody body =
          case eitherDecode' body of
            Left err -> fail err
            Right val -> return val