[ENGLISH] - język polski poniżej!
In the last tutorial, we installed Python and Visual Studio Code, so it's time to put them to use. We will write a simple script that will fetch the current price of Bitcoin using the Coingecko API.
How to code
- We're going to download a library using the pip tool that comes with the Python package. To do this, we need to open the console in our VSCode using the shortcut CTRL + Shift + ` and then type the following commands:
pip install requests
- We're importing the requests library, which is one of the most commonly used libraries in the Python language.
import requests
- We're creating a variable called url and assigning it the API endpoint from Coingecko.
url = "https://api.coingecko.com/api/v3/coins/bitcoin"
- We're creating another variable, this time called parameters, and assigning it an object:
parameters = { "localization": "false", "tickers": "false", "market_data": "true", "community_data": "false", "developer_data": "false", "sparkline": "false" }
- We're making a request by passing the variables url and parameters as arguments to the get method of the requests class (object):
response = requests.get(url, params=parameters)
- We're assigning the response to the variable data in the form of a JSON object.
data = response.json()
- We're extracting the price from the returned object and assigning it to the variable price:
price = data["market_data"]["current_price"]["usd"]
- We're displaying the current price of Bitcoin in the console using the print function.
print("Current price:", price)
For the lazy ones, here's the entire code:
import requests url = "https://api.coingecko.com/api/v3/coins/bitcoin"
parameters = { "localization": "false", "tickers": "false", "market_data": "true", "community_data": "false", "developer_data": "false", "sparkline": "false" }
response = requests.get(url, params=parameters) data = response.json()
price = data["market_data"]["current_price"]["usd"]
print("Current price:", price)
The code can be enhanced with an option to choose a currency and playing around with Coingecko API parameters. It all depends on your willingness and creativity.
Summary
The main takeaways from this tutorial are understanding what a variable is and what objects are. In future tutorials, there will be code that you can use to do something, so your task will be to delve into the key concepts of the language because the basis of programming is searching for information and reading documentation. Without that, you won't be able to write a program that someone else hasn't written because everything will be a problem for you. Programming requires independent thinking, and what I'm doing is just an attempt to inspire others and show that sometimes you can do more with a few simple lines of code than you think.