Skip to content

check_content_type causes error in resp_body_json for cached requests (status 304) #277

@jemus42

Description

@jemus42

When making an API request that has a cached response, resp_body_json throws an error unless check_type = FALSE.

Reprex using a boiled down version of my API wrapper:

library(httr2)

req <- request("https://api.trakt.tv/users/jemus42/comments/all/episodes?include_replies=false") |>
  req_headers(
    # Additional headers required by the API
    "trakt-api-key" = "12fc1de7671c7f2fb4a8ac08ba7c9f45b447f4d5bad5e11e3490823d629afdf2",
    "Content-Type" = "application/json",
    "trakt-api-version" = 2
  ) |>
  httr2::req_retry(max_tries = 2) |>
  httr2::req_cache(path = tempdir(), use_on_error = TRUE, debug = TRUE)

httr2::req_dry_run(req)
#> GET /users/jemus42/comments/all/episodes?include_replies=false HTTP/1.1
#> Host: api.trakt.tv
#> User-Agent: httr2/0.2.3.9000 r-curl/5.0.2 libcurl/7.88.1
#> Accept: */*
#> Accept-Encoding: deflate, gzip
#> trakt-api-key: 12fc1de7671c7f2fb4a8ac08ba7c9f45b447f4d5bad5e11e3490823d629afdf2
#> Content-Type: application/json
#> trakt-api-version: 2
resp_first <- httr2::req_perform(req)
#> Saving response to cache "b2b3e9120f4a602db8b46ba633aa8027"

response_parsed <- httr2::resp_body_json(resp_first)

resp_second <- httr2::req_perform(req)
#> Found url in cache "b2b3e9120f4a602db8b46ba633aa8027"
#> Cached value is stale; checking for updates
#> Cached value still ok; retrieving body from cache
response_parsed <- httr2::resp_body_json(resp_second)
#> Error in if (!is.null(suffix) && endsWith(content_type, suffix)) {: missing value where TRUE/FALSE needed

# Current workaround: disabling content type check
response_parsed <- httr2::resp_body_json(resp_second, check_type = FALSE)

Created on 2023-08-11 with reprex v2.0.2

I found that resp_content_type(resp) can return NA_character here:

httr2/R/resp-headers.R

Lines 101 to 107 in d789827

resp_content_type <- function(resp) {
if (resp_header_exists(resp, "content-type")) {
parse_media(resp_header(resp, "content-type"))$type
} else {
NA_character_
}
}

which causes a missing value where TRUE/FALSE needed error in the if condition here:

httr2/R/resp-body.R

Lines 130 to 133 in d789827

content_type <- resp_content_type(resp)
if (content_type %in% types) {
return()
}

I'm not sure I'm doing caching correctly (I'm in the process of migrating from httr to httr2 and did no caching previously), but I assume that at least this particular error is not the result of me holding it wrong or the trakt.tv API being weird (which is unfortunately the case when it comes to OAuth, but that's a different issue).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions