Search code examples
pythonrequestbitcoin

Can someone explain how this "request" code works?


I am using the following code to get BTC data from coinbase. I just copied this from a tutorial but I want to know how it actually works. Can someone explain step by step? Thank you

import requests # imports the request library

url = "https://api.exchange.coinbase.com/products/BTC-USD/book?level=1" # provides the url from which data will be pulled

headers = {"Accept": "application/json"} # I don't understand the point of this line

response = requests.request("GET", url, headers=headers) # I just don't understand the point of the 'header' part

print(response.text) # This just prints the result

This is the result of the above code:

{"bids":[["45890.49","0.02316146",1]],
 "asks":[["45896.07","0.03631374",1]],
 "sequence":35929645093,
 "auction_mode":false,
 "auction":null}

I understand all this data, just not how the code gets it


Solution

  • Your code sends a GET request to https://api.exchange.coinbase.com/products/BTC-USD/book?level=1 with additional HTTP Headers:

    Accept: application/json
    

    This results in the webserver to send the result of your query in a JSON-Format, which you can access using response.text