Search code examples
rcurlhttr

post request with httr


I am new to httr. I am trying to use this geocoding api: https://geo.api.gouv.fr/adresse. I want to pass a csv file directly from R, as given in their example:

curl -X POST -F data=@search.csv -F columns=adresse -F columns=postcode https://api-adresse.data.gouv.fr/search/csv

The example csv is here: https://adresse.data.gouv.fr/exemples/search.csv

I tried, without specifying the columns:

library(httr)
test <- POST("https://api-adresse.data.gouv.fr/search/csv/", 
      body = "data = @search.csv")

> test
Response [https://api-adresse.data.gouv.fr/search/csv/]
  Date: 2021-02-09 21:27
  Status: 400
  Content-Type: application/json; charset=utf-8
  Size: 66 B

Or

test <- POST("https://api-adresse.data.gouv.fr/search/csv/", 
     body = "data = @search.csv",
     content_type("application/json"))

But i still get 400 status. Specifying the whole file path did not work either. How does this work ? I would like to get the json, and read it in R Thanks in advance !


Solution

  • I am not sure you can request to get json back, but here is how you might do this with httr:

    library(httr)
    
    r <- POST(url = "https://api-adresse.data.gouv.fr/search/csv",
              body = list(data = upload_file("search.csv"), 
                          columns = "adresse", 
                          columns = "postcode"))
    content(r)
    
    # # A tibble: 4 x 20
    #   nom   adresse postcode city  latitude longitude result_label result_score result_type result_id
    #   <chr> <chr>      <dbl> <chr>    <dbl>     <dbl> <chr>               <dbl> <chr>       <chr>    
    # 1 Écol~ 6 Rue ~    54600 Vill~     48.7      6.15 6 Rue Alber~         0.96 housenumber 54578_00~
    # 2 Écol~ 6 Rue ~    54500 Vand~     48.7      6.15 6 Rue d’Aqu~         0.96 housenumber 54547_00~
    # 3 Écol~ 31 Rue~    54180 Heil~     48.6      6.21 31 Rue d’Ar~         0.96 housenumber 54257_00~
    # 4 Écol~ 1 bis ~    54250 Cham~     48.7      6.16 1 bis Rue d~         0.95 housenumber 54115_01~
    # # ... with 10 more variables: result_housenumber <chr>, result_name <chr>, result_street <lgl>,
    # #   result_postcode <dbl>, result_city <chr>, result_context <chr>, result_citycode <dbl>,
    # #   result_oldcitycode <lgl>, result_oldcity <lgl>, result_district <lgl>