Football Prediction API
  • Overview
  • Getting started
    • Setup
    • Making a first API call
    • API Endpoints
  • Api Examples
    • Get sorted predictions for tomorrow
  • Zapier (beta)
    • Setup
    • Connect to Zapier
    • Recipes
Powered by GitBook
On this page
  • Python
  • Node JS
  • Java

Was this helpful?

  1. Api Examples

Get sorted predictions for tomorrow

Python

Dependencies

pip install requests pytz

Code

from datetime import datetime, timedelta, timezone
import os

import requests
import pytz


api_tz = pytz.timezone("Europe/London")

# Change this to your timezone
local_tz = pytz.timezone("Europe/Rome")


def get_current_datetime_on_api_server():
    london_time = datetime.now(tz=timezone.utc).astimezone(api_tz)
    return london_time


def to_local_datetime(start_date):
    dt = datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%S")
    return api_tz.localize(dt).astimezone(local_tz)


if __name__ == "__main__":
    # this is a datetime object with the timezone used by our api
    current_server_time = get_current_datetime_on_api_server()

    # obtaining the next day as python date object
    tomorrow = current_server_time.date() + timedelta(days=1)

    # setting our API key for auth
    headers = {
        'User-Agent': 'python_requests',
        "X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"],
    }

    session = requests.Session()
    session.headers = headers

    # setting our query params
    params = {
        "iso_date": tomorrow.isoformat(), # python date object should be transformed to ISO format (YYYY-MM-DD)
        "federation": "UEFA",
        "market": "classic"
    }

    prediction_endpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions"
    response = session.get(prediction_endpoint, params=params)

    if response.ok:
        json = response.json()
        json["data"].sort(key=lambda p: p["start_date"])

        for match in json["data"]:
            # going to print tab separated start_time, home_team vs away team, prediction @ predicted odds.
            output = "{st}\t{ht} vs {at}\t{p} @ {odd}"

            local_start_time = to_local_datetime(match["start_date"])
            home_team = match["home_team"]
            away_team = match["away_team"]
            prediction = match["prediction"]

            if "odds" in match:
                prediction_odds = match["odds"].get(prediction, None)
            else:
                # user is not able to see odds as it's subscription plan does not support it.
                prediction_odds = None

            print(output.format(st=local_start_time, ht=home_team, at=away_team, p=prediction, odd=prediction_odds))
    else:
        print("Bad response from server, status-code: {}".format(response.status_code))
        print(response.content)

Node JS

Dependencies

npm install moment-timezone axios

Code

const moment = require("moment-timezone");
const axios = require("axios");

const API_TZ = "Europe/London";
const LOCAL_TZ = "Europe/Rome";

// read the current time in the API timezone
const now = moment.tz(API_TZ);
const tomorrow = now.add(1, "days");

const predictionEndpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions";
// setting our API key for auth
// this info should be kept out of public git or other versioning software
const authHeader = {
    "X-RapidAPI-Key": process.env.RAPIDAPI_KEY
}
const params = {
    iso_date: tomorrow.format("YYYY-MM-DD"), // transforming to ISO format.
    federation: "UEFA",
    market: "classic"
}

const opts = {
    method: "GET",
    headers: authHeader,
    params: params
}

axios
    .get(predictionEndpoint, opts)
    .then(response => {
        const json = response.data;

        json.data.sort((a, b) => {
            // sort ascending by start_date
            if (a.start_date > b.start_date)
                return 1;
            if (a.start_date < b.start_date)
                return -1;
            return 0;
        });

        json.data.forEach(match => {
            const locStartDate = moment.tz(match.start_date, API_TZ).tz(LOCAL_TZ);
            let winOdds;

            if (match.odds && match.prediction in match.odds) {
                winOdds = (
                    match.odds[match.prediction] !== null ?
                        match.odds[match.prediction].toFixed(2)
                        : ""
                );
            } else {
                // Not able to see odds as the subscription plan does not support it.
                // or current match does not have the odds available for this prediction
                winOdds = "n/a";
            }
            console.log(`${locStartDate}\t${match.home_team} vs ${match.away_team}\t${match.prediction} @ ${winOdds}`)
        })
    })
    .catch(err => {
        console.log(err.message);
    });

Java

Dependencies

pom.xml
<dependency>
  <groupId>com.mashape.unirest</groupId>
  <artifactId>unirest-java</artifactId>
  <version>1.4.9</version>
</dependency>

Code

package Example;

import com.mashape.unirest.http.*;
import org.json.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;


public class Example {

    private static String API_TZ = "Europe/London";
    private static String LOCAL_TZ = "Europe/Rome";
    private static String predictionEndpoint = "https://football-prediction-api.p.rapidapi.com/api/v2/predictions";

    private static String getAuthKey() {
        return System.getenv("RAPIDAPI_KEY");
    }

    private static ZonedDateTime getApiTimestamp() {
        return ZonedDateTime.now(ZoneId.of(API_TZ));
    }

    private void getPredictions() throws Exception {
        String tomorrow = getApiTimestamp().plusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
        System.out.println("Current API_TZ timestamp: " + getApiTimestamp().toString());
        System.out.println("Tomorrow is: " + tomorrow);

        HttpResponse<JsonNode> response = Unirest
                .get(predictionEndpoint)
                .header("X-RapidAPI-Key", getAuthKey())
                .queryString("federation", "UEFA")
                .queryString("market", "classic")
                .queryString("iso_date", tomorrow)
                .asJson();

        JSONArray jsonArray = response.getBody().getObject().getJSONArray("data");

        if (jsonArray == null) {
            return;
        }

        List<JSONObject> jsonAsList = new ArrayList<JSONObject>();
        for (int i = 0; i < jsonArray.length(); i++)
            jsonAsList.add(jsonArray.getJSONObject(i));

        jsonAsList.sort(new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                String st1 = a.getString("start_date");
                String st2 = b.getString("start_date");
                return st1.compareTo(st2);
            }
        });

        for (JSONObject match : jsonAsList) {

            LocalDateTime dt = LocalDateTime.parse(match.getString("start_date"));
            ZonedDateTime apiDt = ZonedDateTime.of(dt, ZoneId.of(API_TZ));
            ZonedDateTime localDt = apiDt.withZoneSameInstant(ZoneId.of(LOCAL_TZ));
            String homeTeam = match.getString("home_team");
            String awayTeam = match.getString("away_team");
            String prediction = match.getString("prediction");
            JSONObject odds = match.optJSONObject("odds");
            String winOdds = "n/a";

            System.out.println("LocalDateTime: " + dt + " vs " + localDt);
            if (odds != null) {
                // set default odds to 0 in case not found.
                double optOdds = odds.optDouble(prediction, 0.0);

                // all valid odds are > 1.0, the rest are defaultValue from above
                if (optOdds > 1.0) {
                    winOdds = String.valueOf(optOdds);
                }
            }
            System.out.println(localDt.toString() + "\t" + homeTeam + " vs " + awayTeam + "\t" + prediction + " @ " + winOdds);
        }
    }

    public static void main(String[] args) {
        Unirest.setTimeouts(10000, 10000);
        Example client = new Example();

        try {
            client.getPredictions();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
PreviousAPI EndpointsNextSetup

Last updated 5 years ago

Was this helpful?