Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to implement a modified "explode" option for .multi in req_url_query()? #593

Closed
Aariq opened this issue Dec 9, 2024 · 4 comments
Closed
Milestone

Comments

@Aariq
Copy link

Aariq commented Dec 9, 2024

I'm working with the usa-npn API which takes multiple values for a query like so: x[1]=1&x[2]=2&x[3]=3. The .multi argument doesn't seem to be able to handle this and I have to construct the list of queries outside of req_url_query(). It seems like there isn't a way for a function supplied to .multi to use the parameter name. E.g., this doesn't work:

library(httr2)

#this sort of thing would be nice
foo <- function(x) {
  x_name <- deparse(substitute(x))
  glue::glue("{x_name}[{seq_along(x)}]={x}") %>% 
    glue::glue_collapse(sep = "&")
}
ID <- 5:7
foo(ID)
#> ID[1]=5&ID[2]=6&ID[3]=7

#but doesn't work here
request("https://example.com") %>% 
  req_url_query(
    ID = 5:7,
    .multi = foo
  )
#> <httr2_request>
#> GET https://example.com?ID=X[[i]][1]=5&X[[i]][2]=6&X[[i]][3]=7
#> Body: empty

Created on 2024-12-09 with reprex v2.1.1

Is there a workaround for this? I looked at the code to figure out what "explode" does, and it seems like it behaves differently from an anonymous function—I couldn't figure it out.

@hadley
Copy link
Member

hadley commented Dec 10, 2024

There's no way to do it currently with .multi because it assumes that the names stay the same. You could however do something like this:

library(httr2)

foo <- function(nm, vals) {
  setNames(vals, paste0(nm, "[", seq_along(vals), "]"))
}
request("https://example.com") |>
  req_url_query(!!!foo("ID", 5:7))

@Aariq
Copy link
Author

Aariq commented Dec 10, 2024

Thanks! That is a much "cleaner" solution than I had before

@hadley hadley added this to the v1.1.0 milestone Dec 19, 2024
@hadley
Copy link
Member

hadley commented Dec 20, 2024

BTW does it still work with your API if you omit the index? i.e. x[]=1&x[]=2&x[]=3. If so you could do:

request("https://example.com") %>% 
  req_url_query(
    `ID[]` = 5:7,
    .multi = "explode"
  )

@Aariq
Copy link
Author

Aariq commented Jan 6, 2025

BTW does it still work with your API if you omit the index? i.e. x[]=1&x[]=2&x[]=3. If so you could do:

request("https://example.com") %>% 
  req_url_query(
    `ID[]` = 5:7,
    .multi = "explode"
  )

I have no idea why, but that does work (at least for the endpoint I tested). Thanks for the suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants