Welcome to the first article in a series of articles on Python projects for beginners!

In this tutorial were going to build a Bitcoin price notification service

During this project youll learn about HTTP requests and how to send them using the (appropriately named)requestspackage.

Youre going to learn about webhooks and how you can use them to connect your Python app to external services, such as phone notifications or Telegram messages.

With relatively little code (~50 lines) youre going to arrive at a full-fledged Bitcoin price notification service that will be easily extendable to other cryptocurrencies and services.

As we all know, Bitcoin price is a fickle thing. You never really know where its going to be at the end of the day. So, instead of constantly checking various sites for the latest updates, lets make a Python app to do the work for you.

For this, were going to use the popular automation websiteIFTTT. IFTTT (if this, then that) is a web service that bridges the gap between different apps and devices.

Were going to create two IFTTT applets:

One for emergency notification when Bitcoin price falls under a certain threshold; and

another for regularTelegramupdates on the Bitcoin price.

Both will be triggered by our Python app which will consume the data from theCoinmarketcap API.

An IFTTT applet is composed of two parts: a trigger and an action.

In our case, the trigger will be a webhook service provided by IFTTT. You can think of webhooks as user-defined HTTP callbacks and you can read more about themhere.

Our Python app will make an HTTP request to the webhook URL which will trigger an action. Now, this is the fun partthe action could be almost anything you want. IFTTT offers a multitude of actions like sending an email, updating a Google Spreadsheet and even calling your phone.

Lets start by setting up avirtual environment. Run this command to get a new Python 3 virtual environment:

Before continuing you have to activate the virtual environment and install the required dependencies:

You can deactivate the virtual environment by running thedeactivateshell command.

Time to get our hands dirty. We can start by getting the latest price from the Coinmarketcap API in the Python console:

First, we have to import therequestsmodule and define thebitcoin_api_urlvariable which contains the Coinmarketcap API URL for Bitcoin.

Next, we send an HTTP GET request to the URL using therequests.get()function and save the response. Since the API returns a JSON response, we can convert it to a Python object by calling the.json()function on the response. As you can see, the API returned a list with one element containing the Bitcoin price data:

Bitcoin data is the first element of the list

id: bitcoin, name: Bitcoin, symbol: BTC, rank: 1,

price_usd: 10226.7, price_btc: 1.0, 24h_volume_usd: 7585280000.0,

market_cap_usd: 5, available_supply: 16883362.0,

total_supply: 16883362.0, max_supply: 21000000.0,

percent_change_1h: 0.67, percent_change_24h: 0.78,

percent_change_7d: -4.79, last_updated: 1519465767

The property that were most interested in isprice_usdthe Bitcoin price in US dollars.

Now we can move onto the IFTTT side of things. To use IFTTT youll first need toset up a new accountand install their mobile app (if you want to receive phone notifications from your Python app). Once you set that up, were going tocreatea new IFTTT applet fortesting purposes.

To create a new test applet follow these steps:

To see the documentation on how to use the IFTTT webhooks go to thispageand click on theDocumentationbutton in the top right corner. The documentation page contains the webhook URL and it looks like this:

Next up, youll need to substitute theeventpart with whatever name you gave our event in step 3, when you created the applet. Theyour-IFTTT-keypart is already populated with your IFTTT key.

Now copy the webhook URL and start another Python console. Again we import therequestsmodule and define the webhook URL variable. Now we just have to send an HTTP POST request to the IFTTT webhook URL using therequests.post()function:

After running the last line you should see a notification on your phone:

Now were finally ready for the main part. Before starting with the code we need to create two new IFTTT applets: one for emergency Bitcoin price notifications and one for regular updates.

Send a rich notification from the IFTTT app

Bitcoin price is at $Value1. Buy or sell now!

Optionally you could add a Link URL to the Coinmarketcap Bitcoin page:

Create the action and finish setting up the applet

Note:When creating this applet you will have to authorize the IFTTT Telegram bot.

Now that we have IFTTT out of the way, lets start coding! Youll start by creating the standard Python command-line app skeleton shown below. Take this code and save it in a file calledbitcoin_notifications.py:

Next, we have to translate the two previous Python console sessions into two functions that will return the latest Bitcoin price and post to the IFTTT webhook respectively. Add the following functions above the main function:

Convert the price to a floating point number

The payload that will be sent to IFTTT service

Sends a HTTP POST request to the webhook URL

Theget_latest_bitcoin_priceis pretty much the same, except for the part where we have to convert the price from a string to a floating point number. Thepost_ifttt_webhooktakes in two parameters:eventandvalue.

Theeventparameter corresponds to whatever event name we gave to our trigger when setting up the IFTTT applet. Also, the IFTTT webhooks allow us to send additional data along with the request as JSON-formatted data.

Thats why we need thevalueparameter: When setting up our applets we left aValue1tag in our message fields. This tag is replaced with thevalue1text from the JSON payload. Therequests.post()function allows us to send additional JSON data just by adding thejsonkeyword.

Now we can move on to the core of our app in themainfunction. It will consist of awhile Trueloop since we want our app to run forever. In the loop we will call the Coinmarketcap API to get the latest Bitcoin price and record the current date and time.

Based on the current price we will decide if we want to send an emergency notification. For our regular Telegram updates we will also append the current price and date to abitcoin_historylist. Once the list reaches a certain number of items (e.g. 5) we will format the items, send the update to Telegram, and reset the history for future updates.

Wheew! As you can see, theres a lot going on in this app. If youre having trouble following the code weve got thus far then take a quick break and re-read the above section again slowly. This stuff isnt easy, so take your time and dont worry about getting everything perfect the first time around.

An important thing is to avoid sending out these requests too frequently, for two reasons:

the Coinmarketcap API states that they update the data only once every 5 minutes, so theres no point in reloading the latest pricing info more frequently than that

if your app sends too many requests to the Coinmarketcap API your IP might get banned or temporarily suspended.

That is why we need to go to sleep (stop the execution of the loop) for at least 5 minutes before we get new data. The code below implements all of the required features I stated above:

Were almost done! The only thing missing is theformat_bitcoin_historyfunction. It takes thebitcoin_historyas an argument and formats it using some of the basic HTML tags allowed by Telegram, likebr,b,i, and so on. Copy this function above themainfunction:

Formats the date into a string: 24.02.2018 15:09

24.02.2018 15:09: $b10123.4/b

Use a br (break) tag to create a new line

Join the rows delimited by br tag: row1brrow2brrow3

This is what the end result should look like on your phone:

To run your price notification app, execute the following in your command-line terminal:

Thats it! In little over 50 lines of Python code, youve created your very own Bitcoin notification service. Congratulations! Below Ive added the entire code so you can compare and see if youve missed anything:

Solution: Python Bitcoin Price NotifierShow/Hide

Convert the price to a floating point number

The payload that will be sent to IFTTT service

Sends a HTTP POST request to the webhook URL

Formats the date into a string: 24.02.2018 15:09

24.02.2018 15:09: $b10123.4/b

Use a br (break) tag to create a new line

Join the rows delimited by br tag: row1brrow2brrow3

Once we have 5 items in our bitcoin_history send an update

Sleep for 5 minutes (for testing purposes you can set it to a lower number)

In this article, we created our very own Bitcoin notification service. You learned how to send HTTP GET and POST requests using therequestspackage. You saw how easy it was to connect your Python app to external services using IFTTT and webhooks.

Now, where should you go next? With Python and IFTTT the sky is the limit. But here are some suggestions that can get you started:

Like spreadsheets? Use an IFTTT action that will add the Bitcoin prices to a Google Spreadsheet

condition to get the notification only once per day (otherwise it will get quite annoying if Bitcoin is consistently low)

Like Ethereum/Litecoin/Dogecoin better? Change the

that will take a cryptocurrency as a parameter and return its price

You want the price in a different currency? Check the Coinmarketcap API for the

Also, this will be an ongoing series with more Python projects you can build to grow your skills. Dont miss out on the next tutorial:

Dont miss the follow up tutorial:Click here to join the Real Python Newsletterand youll know when the next installment comes out.

Good luck and Happy Pythoning! Let me know what youve built using Python and IFTTT in the comments below!

Get a short & sweetPython Trickdelivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Rok is a software engineer from Slovenia. Member of the Real Python Tutorial Team.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Real Python Comment Policy:The most useful comments are those written with the goal of learning from or helping out other readersafter reading the whole article and all the earlier comments. Complaints and insults generally wont make the cut here.

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Almost there! Complete this form and click the button below to gain instant access:

Join the Real Python Community Newsletter (More Than 45,468 Python Developers Have Subscribed)

© 20122019 Real Python ⋅NewsletterYouTubeTwitterFacebookInstagram

Python TutorialsSearchPrivacy PolicyAdvertiseContact