Connor Mills

Connor Mills

1552965149

How to Use Python With Real-Time Data and REST APIs?

#python #rest #api

What is GEEK

Buddha Community

Edward Jackson

1552965888

We take a look at how to use Python and a freely available REST API to call, manipulate, and display data on our machine.

1. Introduction

The Forex Quote API provided by 1forge.com is one of the most generous places with free plans to get real-time currency exchange values. The https://1forge.com/forex-data-api site includes an introduction to the Forex data API.

For free accounts, the REST rate limit is 1000 requests per day returning results in JSON format. It supports more than 700 currency pairs. Unfortunately, the Peruvian Sol (PEN) is not supported.

You have to obtain an API key to submit requests. For that, you can register at https://1forge.com/register and, finally, in your free account, you can get your API key.

In order to learn which data type is returned, you can submit a raw request via your favorite web browser, including the currency pairs and your API key, such as:

[https://forex.1forge.com/1.0.3/quotes?pairs=EURUSD,GBPJPY,AUDUSD&api_key="your_api_key"](https://forex.1forge.com/1.0.3/quotes?pairs=EURUSD,GBPJPY,AUDUSD&api_key="your_api_key" "https://forex.1forge.com/1.0.3/quotes?pairs=EURUSD,GBPJPY,AUDUSD&api_key="your_api_key"")

[{"symbol":"EURUSD","bid":1.12333,"ask":1.12335,"price":1.12334,"timestamp":1552081127},
 {"symbol":"GBPJPY","bid":144.677,"ask":144.683,"price":144.68,"timestamp":1552081127},
 {"symbol":"AUDUSD","bid":0.70454,"ask":0.70456,"price":0.70455,"timestamp":1552081127}]

As you can see, the REST call returns a list of key values.

Please note that I am not using the Python client. Instead, I am using REST calls to the API. Also please note that over the weekends there are no currency updates via this API, as compared to other sites such as the XE currency converter.

REST API calls include (taken from the Forex site):

2. Analysis of Code Excerpts

In this case, I am working with a Python script that gets the currency exchange values of Euros compared to US Dollars and vice-versa. The code executes a REST request for getting the respective quotes.

2.1 Initial Code: Import Statements and Global Variables

import requests
import json
import datetime
from tkinter import *
import time

api_key = "your_api_key"
pairs = "EURUSD,USDEUR"
url = "https://forex.1forge.com/1.0.3/quotes?pairs=" + pairs + "&api_key=" + api_key

In this first code excerpt, we import the required libraries and set up the API key and the currency pairs to form the final URL where we’ll send the REST request.

2.2 Get Currency Values Code Excerpt

def get_currency_values():
    """
        Returns currency pair values
        :return: currency pair values.
        Example EURUSD 1.1239 (euro to dollar conversion)
    """

    response = requests.get(url)

    data = response.text
    currencies = json.loads(data)
    forex_currencies = []

    for currency in currencies:
        for key, value in currency.items():
            if key == "symbol":
                symbol_from = value[:3]
                symbol_to = value[3:]
                str_currency = symbol_from + " TO " + symbol_to + ": "
            if key == "price":
                price = value
        forex_currencies.append(str_currency  + str(price))

    return forex_currencies

In this code snippet, we process the raw REST request and format it into a list of currency pairs with its respective values: for instance EUR to USD: 1.12329

2.3 Set Up GUI Window Elements

In the code excerpt depicted below, we set up the GUI Window with three labels, one containing the date/time and other labels depicting currency pair values. In this case Euro to Dollar and Dollar to Euro, the script can be customized to include the required currencies (may require you to add labels to the main window).

def setup_gui(window, symbol_pairs):
    """
        Returns a window with labels representing currency pairs information (prices)

        :param window: window to be setup with labels
        :param symbol_pairs: the symbol pairs with associated currency values
        :return: Returns a window with time, and currency pairs with associated currency values
    """

    window.wm_title("Currency Table")

    date_time = datetime.datetime.now().strftime("%A %d %B %Y %H:%M:%S:%f")
    str_date_time = "On " + str(date_time)

    l1 = Label(window, text=str_date_time)
    l1.grid(row=0, column=0)

    l2 = Label(window, text=symbol_pairs[0])
    l2.grid(row=1, column=0)

    l3 = Label(window, text=symbol_pairs[1])
    l3.grid(row=2, column=0)

    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()

    # currency window info positioned on the lower right side of the screen
    # and with a given screen width and height
    xpos = screen_width - 250
    ypos = screen_height - 150
    window.geometry("250x75+" + str(xpos) + "+" + str(ypos))

    return window


2.4 Code Excerpt Setting Up A Top Window With Date/Time & Currency Pairs Values

Finally, we set up the window so that currency information is always showing at the top of other windows:

def main():    
    while True:
        window = Tk()
        symbol_pairs = get_currency_values()
        window = setup_gui(window, symbol_pairs)        
        window.update()        

        # let the window be always on top of other windows        
        window.lift()        
        window.attributes('-topmost', True)        

        # we get the next currency pair values every 60 seconds        
        time.sleep(60)        
        window.destroy()

if __name__ == '__main__':    
    main()

3. Whole Code Script

And this is the whole Python script:

import requests
import json
import datetime
from tkinter import *
import time

api_key = "your_api_key"
pairs = "EURUSD,USDEUR"
url = "https://forex.1forge.com/1.0.3/quotes?pairs=" + pairs + "&api_key=" + \
      api_key

def get_currency_values():
    """
        Returns currency pair values
        :return: currency pair values.
        Example EURUSD 1.1239 (euro to dollar conversion)
    """

    response = requests.get(url)

    data = response.text
    currencies = json.loads(data)
    forex_currencies = []

    for currency in currencies:
        for key, value in currency.items():
            if key == "symbol":
                symbol_from = value[:3]
                symbol_to = value[3:]
                str_currency = symbol_from + " TO " + symbol_to + ": "
            if key == "price":
                price = value
        forex_currencies.append(str_currency  + str(price))

    return forex_currencies

def setup_gui(window, symbol_pairs):
    """
        Returns a window with labels representing currency pairs information (prices)

        :param window: window to be setup with labels
        :param symbol_pairs: the symbol pairs with associated currency values
        :return: Returns a window with time, and currency pairs with associated currency values
    """

    window.wm_title("Currency Table")

    date_time = datetime.datetime.now().strftime("%A %d %B %Y %H:%M:%S:%f")
    str_date_time = "On " + str(date_time)

    l1 = Label(window, text=str_date_time)
    l1.grid(row=0, column=0)

    l2 = Label(window, text=symbol_pairs[0])
    l2.grid(row=1, column=0)

    l3 = Label(window, text=symbol_pairs[1])
    l3.grid(row=2, column=0)

    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()

    # currency window info positioned on the lower right side of the screen
    # and with a given screen width and height
    xpos = screen_width - 250
    ypos = screen_height - 150
    window.geometry("250x75+" + str(xpos) + "+" + str(ypos))

    return window

def main():

    while True:

        window = Tk()
        symbol_pairs = get_currency_values()
        window = setup_gui(window, symbol_pairs)
        window.update()

        # let the window be always on top of other windows
        window.lift()
        window.attributes('-topmost', True)

        # we get the next currency pair values every 60 seconds
        time.sleep(60)
        window.destroy()

if __name__ == '__main__':
    main()

4. Setting Up Automatic Script Execution in a Windows 10 Environment

The final step is to rename the file to “forex.pyw” (or any name you want, really; just make sure to end the name of the file with the “.pyw” extension, because it is a GUI application):

This is the final resulting window that appears on top of other windows and changes the currency values every 60 seconds:

If you are running this script on Windows, you can enable the automatic execution of the script when logging in to your user account, by following these steps:

Create a Windows link in "C:\Users\YourUserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup with the following properties:

Given that I am no Linux expert I am not sure if you can run an equivalent “cron job.”

For those that require continuous information about real-time currency exchange values, this Python script will be really helpful.

Learn More

An A-Z of useful Python tricks

Learning Python: From Zero to Hero

Top REST API Best Practices

How to build a Rest API with Spring Boot using MySQL and JPA?

Build a Simple REST API in PHP

Build a Simple REST API with Node and OAuth 2.0

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ian  Robinson

Ian Robinson

1621644000

4 Real-Time Data Analytics Predictions for 2021

Data management, analytics, data science, and real-time systems will converge this year enabling new automated and self-learning solutions for real-time business operations.

The global pandemic of 2020 has upended social behaviors and business operations. Working from home is the new normal for many, and technology has accelerated and opened new lines of business. Retail and travel have been hit hard, and tech-savvy companies are reinventing e-commerce and in-store channels to survive and thrive. In biotech, pharma, and healthcare, analytics command centers have become the center of operations, much like network operation centers in transport and logistics during pre-COVID times.

While data management and analytics have been critical to strategy and growth over the last decade, COVID-19 has propelled these functions into the center of business operations. Data science and analytics have become a focal point for business leaders to make critical decisions like how to adapt business in this new order of supply and demand and forecast what lies ahead.

In the next year, I anticipate a convergence of data, analytics, integration, and DevOps to create an environment for rapid development of AI-infused applications to address business challenges and opportunities. We will see a proliferation of API-led microservices developer environments for real-time data integration, and the emergence of data hubs as a bridge between at-rest and in-motion data assets, and event-enabled analytics with deeper collaboration between data scientists, DevOps, and ModelOps developers. From this, an ML engineer persona will emerge.

#analytics #artificial intelligence technologies #big data #big data analysis tools #from our experts #machine learning #real-time decisions #real-time analytics #real-time data #real-time data analytics

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

REST API In Laravel Example

Hello Friends,

Today I will give you information about REST API, REST API is an application program interface that uses HTTP requests to GET, PUT, POST and DELETE data.

In this tutorial I am going to perform CRUD operation using REST API and you can learn how to create REST API with authentication using passport in laravel 6/7 application. here we will get data from API.

REST API In Laravel Example

https://websolutionstuff.com/post/rest-api-in-laravel

#rest api in laravel example #php #rest api #crud operation using rest api #rest api with passport #laravel rest api crud