
Contents
What is Node.js?
Node.js is a JavaScript runtime environment that allows you to execute JavaScript code server-side (on the server). It’s built on Chrome’s V8 JavaScript engine and uses a non-blocking, event-driven architecture, making it highly efficient for building scalable network applications.
What is TypeScript?
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static typing, interfaces, and other features that enhance code maintainability and help catch errors during development. Typescript is particularly useful for building large-scale applications where type safety is crucial.
Why use Node.js and TypeScript together?
Here’s why they work so well together:
– Fewer errors: TypeScript helps you catch mistakes before your app is running, which means less debugging and a smoother experience for everyone.
– Easier to understand: TypeScript makes your code neater and easier to follow, which is a lifesaver when you’re working on a big project or coming back to old code.
– Better tools: TypeScript gives you better tools in your code editor, making it quicker and easier to write code.
– Stronger foundation: Node is already great for building server-side logic, and TypeScript makes it even more reliable and easier to maintain.
Who uses Node.js and TypeScript, and what are they used for?
Both Node and TypeScript are popular tools used by lots of developers.
Node is like a versatile toolbox for building web applications:
– Websites and APIs: It’s great for building the behind-the-scenes parts of websites and applications that need to handle lots of users at the same time.
– Small, connected services: It can create small, independent parts of an application that work together.
– Command-line tools: It helps build tools you can use in your computer’s terminal.
– Backend for interactive websites: It powers the behind-the-scenes logic for websites built with popular frameworks like React, Angular, and Vue.js.
Big companies like Netflix, PayPal, LinkedIn, and Uber use Node.
TypeScript is like a more organised and helpful version of javascript:
– Big web applications: It’s used for complex web apps where it’s important to keep the code clean and prevent errors.-
Angular development: It’s the main language for building applications with Angular.
– React development: It’s becoming more popular with React developers too.
– Node.js development: Using it with node makes coding easier and improves the quality of your code.
Companies like Microsoft (who created it), Asana, Slack, and Airbnb use typescript.
Together, node and typescript are a powerful combination for building strong and reliable web applications.
Chapter 1: Setting up your environment
Let’s get your development environment ready.
1.1 Installing node and npm
Download and install node and npm from the official node.js website if you haven’t already.
1.2 Creating a new project
Open your terminal and create a new directory for your project:
mkdir football-predictions cd football-predictions
Initialise a new node project:
npm init -y
1.3 Installing TypeScript and dependencies
Install TypeScript and the necessary dependencies:
npm install typescript @types/node axios @types/axios
1.4 Configuring TypeScript
Initialise a TypeScript configuration file:
tsc --init
1.5 Setting up automatic TypeScript compilation
Modify the typescript configuration file (tsconfig.json) in your project root:
{ "compilerOptions": { "target": "es2018", "module": "commonjs", "outDir": "./dist", "rootDir": "./", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["./**/*.ts"], "exclude": ["node_modules"] }
Then add these scripts to your package.json:
{ "scripts": { "watch": "tsc -w", "start": "node dist/index.js" } }
After that, open a terminal in your IDE and run:
npm install typescript --save-dev
Start the watch mode by running:
npm run watch
Now TypeScript will automatically compile your .ts files to .js files in the dist directory whenever you make changes. To run your compiled code:
npm start
You can keep two terminal windows open in your IDE:
- One running npm run watch for compilation
- Another for running npm start to execute your code
The compiled JavaScript will be in dist/index.js, and it will update automatically when you save changes to your TypeScript files.
Chapter 2: Fetching predictions via fixture ID
Before we can fetch predictions using SportMonks’ Football API, let’s ensure you have everything set up.
2.1 Setting up your API token
To interact with the API, you’ll need an API token. Follow these steps:
- Sign up or log in to your Sportmonks account at my.sportmonks.com.
- Your account includes free access to the Danish Superliga and Scottish Premier League plans.
- If needed, start a 14-day free trial for any other plans.
- Navigate to the tokens section and create a new token.
- Copy the generated token and keep it handy—we’ll use it in the code.
2.2 Finding the Fixture ID
To fetch predictions, you need a fixture ID. Here’s how to find it:
Go to Resources > ID Finder.
Select League IDs and locate the league you’re interested in.
Once you’ve found the league, click on the “current league id” to open the list of fixtures.
Identify the specific fixture you want predictions for and note its fixture ID (In this case, we’re using the Manchester City vs Liverpool fixture).
2.3 Writing the code
Now that we have our token and fixture ID, let’s write the code to fetch predictions.
2.3.1 Creating the index.ts file
Create a new file named index.ts and add the following code:
import axios from "axios"; // API configuration object const config = { apiKey: "YOUR_API_TOKEN", // Replace with your actual API token baseUrl: "https://api.sportmonks.com", version: "v3", sport: "football", }; /** * Fetches match predictions from SportMonks API for a given fixture ID * @param fixtureId - The ID of the fixture to get predictions for */ async function fetchPredictions(fixtureId: number) { // Construct API endpoint URL const url = `${config.baseUrl}/${config.version}/${config.sport}/predictions/probabilities/fixtures/${fixtureId}`; try { // Make API request with authentication const response = await axios.get(url, { params: { api_token: config.apiKey, }, }); // Log formatted prediction data console.log( `Prediction for fixture ${fixtureId}:`, JSON.stringify(response.data, null, 2) ); } catch (error) { // Handle API-specific errors if (axios.isAxiosError(error)) { console.error("Error fetching prediction:", error.message); if (error.response) { console.error("API Response:", error.response.data); } } else { // Handle unexpected errors console.error("Unexpected error:", error); } } } // Example usage with a specific fixture ID const fixtureId = 19134590; fetchPredictions(fixtureId);
2.4 Running the code
- Ensure you’ve replaced YOUR_API_TOKEN with the token you generated.
- Replace 19134590 with the actual fixture ID you want.
- Run the script in your terminal:
npm start
Testing your code now gives;
As we can see, our API gives the home team (Manchester City) a 42.53% chance of winning, the away team (Liverpool) a 32.66% chance of winning and a 24.78% chance of both teams sharing the points.
Chapter 3: Adding details to the prediction data
To get a more refined response from our API, we offer a couple of filters which can add more details to our api.
- Adding details by type: This involves tweaking the url and appending an include value of type, to get the type of prediction information in your response. To do this, add &include=type to your api url.
const url = `${config.baseUrl}/${config.version}/${config.sport}/predictions/probabilities/fixtures/${fixtureId}&include=type`;
And this gives;
2. Adding details by fixture: This step is similar to the first, but involves a different includes value, and yields information about the fixture like the teams playing, the venue, the duration of the match, etc. Simply add ?&include=fixture to your url.
const url = `${config.baseUrl}/${config.version}/${config.sport}/predictions/probabilities/fixtures/${fixtureId}&include=fixture`;
And the result is;
Other predictability APIs
We also offer access to other prediction data sources via our API like
– Value bet API: This endpoint helps get you all the bookies data about a particular fixture and returns some information like the bookmaker name, the odds and so on.
– League predictability API: This endpoint is useful for getting useful betting information on a particular league based on historical data from that league. This endpoint returns information such as the likelihood of goals being scored, the total goals, when the goals are scored etc.
Sportmonks provides these excellent API and more which your team can use to build high-quality football applications. Not convinced? Head over to Sportmonks to try it out today. Alternatively, we offer a 14 day free trial if you’re still on the fence.
Conclusion
This tutorial has provided a comprehensive guide to building a football prediction application using the Sportmonks prediction API, Node.js, and TypeScript. We covered setting up your development environment, fetching predictions via fixture ID, and exploring ways to enrich the prediction data with additional details like prediction type and fixture information.
We also briefly touched upon other valuable prediction APIs offered by Sportmonks, such as the Value Bet API and the League Predictability API, which can provide even deeper insights into your application
We encourage you to explore the Sportmonks API documentation further, experiment with different endpoints and parameters, and build upon this example to create your unique football prediction applications. Start your free trial today and unlock the world of football data!