mercredi 19 août 2020

Want to write a for loop that calls an API with some conditions (if/else)

I want to call an Api that gives me all my shop orders. I have a total of 86.000 orders where the ID of the first order is 2 and the ID of the most recent order is 250.000. Orders obviously are not count consecutive, due to some reason i dont know yet, but doesnt matter.

I started a simple script with a for loop where the ID gets updated in every loop, like this:

library(jsonlite)
library(httr)

user = "my_name"
token = "xyz"

y = 0
urls = rep("api.com/orders/", 250000)

for(i in urls){

y = y + 1

url = paste0(i, y)

a = httr::GET(url, authenticate(user, token))
a_content = httr:content(a, as = "text", encoding = "UTF-8")
a_json = jsonlite::fromJSON(a_content, flatten = T)
...
}

Problem here is, whenever there is an ID with no order, the loop stops with "{\"success\":false,\"message\":\"Order by id 1 not found\"}" So i somehow have to expand the code with some if else statements, like 'if the id does not match an order proceed to the next order'. Also i want to write all orders into a new list. Any help apprichiated.

Aucun commentaire:

Enregistrer un commentaire