Ruby: Get the tracking information from the UPS API (without login)

1k Views Asked by At

I built a ruby on rails web application that parse the tracking information of UPS shipments from "https://www.ups.com/track/api/Track/GetStatus". Since yesterday, I start receiving 401 errors and I am no longer able to retrieve the tracking information of the shipments.

I tried to add a "X-XSRF-Token" header to my request. But I still receiving the same "#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>" response with its body equals to {"unauthorized":401}. Is there anything I am doing wrong?

This is the code I try to implement:

    uri = URI("https://www.ups.com/track/api/Track/GetStatus")
    res = Net::HTTP.get_response(uri)
    xsrf_token = res.to_hash['set-cookie'][1].split("\;")[0].split("X-XSRF-TOKEN-ST=")[1]
    
    header = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-Requested-With": "XMLHttpRequest",
      "X-XSRF-Token": xsrf_token
    }

    body = {
        "TrackingNumber": ["my ups tracking number"],
    }

    request = Net::HTTP::Post.new(uri, header)
    request.body = body.to_json

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    response = http.request(request)

EDIT (Solution):

Thank you tadman for your answer. One solution is indeed to send the cookies with the request.

    header = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-Requested-With": "XMLHttpRequest",
      "X-XSRF-Token": xsrf_token,
      "Cookie": res.to_hash['set-cookie'][0]
    }
1

There are 1 best solutions below

0
On BEST ANSWER

It's often the case that tokens like that are bound to your session, something typically established via one or more cookies that are sent in conjunction with the request, and it may be invalid if those cookies are absent.

It may also be locked to a particular IP or browser. These can be implemented many different ways. The idea is to make it as non-reusable as possible, so you're going to have to fight against that.

In the end it might be easier to establish your own session using cookie persistence and get a fresh token for this task.