Home/Blog/Betfair API — Getting Started
Sub Article · Software Deep Dives

Betfair API — Getting Started Developer Guide (2026)

The Betfair Exchange API gives you everything Bet Angel and Geeks Toy use under the hood — in raw JSON. This is the on-ramp for developers: how to get an app key, generate your SSL certificate, log in with the Python SDK, list markets, read live prices, place your first bet, and stay inside the rate limits.

Updated 18 May 202613 min readAPI · Developer

When (and when not) to use the API

The Betfair Exchange API is the developer-grade interface to the exchange. It gives you everything Bet Angel and Geeks Toy use under the hood, but in raw JSON form. It is the right choice if you can code and if your strategy needs something off-the-shelf software can't give you. It is the wrong choice if you mostly need a ladder and a few automation rules — Bet Angel's Guardian (covered in Bet Angel Guardian: Automation) is faster to deploy and doesn't require you to maintain code.

The full cluster context is at the pillar — Betfair Trading Software — Complete Reviews. This piece is the on-ramp specifically for developers.

Prerequisites and costs

  • Funded Betfair Exchange account. Open one if you haven't — see account setup.
  • Application key. Free "live" key on request, or paid "delayed" key from £200 one-off.
  • Programming language. Python is by far the most common. Java, C#, and Node have working SDKs too.
  • OpenSSL. For the certificate-based login flow.
  • A small dev environment. A laptop or any VPS will do — there's no heavy compute requirement.

Total upfront cost: free if you only need the delayed-data key for paper trading, around £200 one-off for the live key. There is no monthly software subscription. Be aware of the commission and possible premium charge implications of API trading.

Step 1 — Get an application key

Log into your Betfair account, navigate to the Developer Programme page, and request an application key. You'll receive two keys — a "delay" key and a "live" key. Use the delay key while you build; switch to the live key before you put real money on.

What you get back
App key (delay)ABCdef123XYZ — for development
App key (live)XYZ987QRSabc — for production
Vendor app keyNot needed for personal use

Step 2 — Generate the SSL certificate

Betfair's non-interactive login requires a client SSL certificate. Generate it once with OpenSSL:

openssl genrsa -out client-2048.key 2048
openssl req -new -x509 -days 1825 -key client-2048.key -out client-2048.crt

Upload the .crt file in your Betfair Account → Security → Automated Login. Keep the .key file secret. We cover the operational side — backups, rotation — in the pillar piece.

Step 3 — Authenticate

Using the betfairlightweight Python library, authentication is three lines:

import betfairlightweight
trading = betfairlightweight.APIClient(username, password, app_key, certs='/path/to/certs')
trading.login()

If you get back a SessionToken, you're in. If you don't, the certificate path is almost always the issue.

Step 4 — First API call

List today's UK horse racing meetings:

from datetime import datetime, timedelta
filter = {'eventTypeIds': ['7'], 'marketCountries': ['GB'],
'marketStartTime': {'from': datetime.utcnow().isoformat(),
'to': (datetime.utcnow()+timedelta(hours=12)).isoformat()}}
markets = trading.betting.list_market_catalogue(filter=filter, max_results=100)

You should see a list of dictionaries, each with a marketId, marketName and runner list. Event type 7 is horse racing; 1 is football; 2 is tennis; 4339 is greyhounds.

Step 5 — Live market prices

To pull live back/lay prices for a market:

price_filter = {'priceData': ['EX_BEST_OFFERS']}
book = trading.betting.list_market_book(market_ids=[market_id], price_projection=price_filter)

The result includes each runner's available-to-back and available-to-lay queues. This is the same data Bet Angel renders on its ladder, just in raw form. We cover how to read it in How to Read the Betfair Market.

Step 6 — Placing your first API bet

The first time you place a real bet through the API is unnerving. Start with the smallest allowed stake (£2) on a low-volume market.

order = {'selectionId': sel_id, 'handicap': 0,
'side': 'BACK', 'orderType': 'LIMIT',
'limitOrder': {'size': 2.00, 'price': 4.0, 'persistenceType': 'LAPSE'}}
resp = trading.betting.place_orders(market_id=market_id, instructions=[order])
First-bet checklist
Stake£2.00 (minimum)
SideBACK (safer than LAY for first try — bounded risk)
MarketLow-volume meeting, not Cheltenham Day 1
PersistenceLAPSE (cancels at off, no in-play exposure)
VerifyOpen Betfair app and check the bet is in your matched list

Cancel the bet immediately after confirming it's there. The point of this step is to prove your pipeline works end-to-end, not to actually trade.

Rate limits and weight

The Betfair API has request weight limits — every call has a "weight" cost and you have a per-second budget. Read-only price calls are cheap; place_orders is heavier. If you exceed the limit you'll get back a INVALID_INPUT_DATA or rate-limit error.

Practical guidance: don't poll list_market_book more than once a second per market in the dev phase. Move to the streaming API (betfairlightweight.streaming) before you scale up — it pushes price updates rather than asking for them, and it's cheaper, faster, and more accurate.

Next steps

Honest warning before you go live

A bug in your bot can place bets you didn't intend. Before turning on automation in production, hard-code a daily stake limit, a per-market stake limit, and a kill-switch you can toggle from a separate terminal. We've seen real bots burn through four-figure sums because of a missing comma. Code defensively.

The main API endpoints you'll use

The Betfair Exchange API has dozens of endpoints; most production trading uses a small subset. The key ones, with their typical purpose:

  • listEventTypes — once a day to enumerate sports. You'll mostly hard-code event type IDs.
  • listCompetitions — competition-level grouping (e.g. "Premier League"). Useful when filtering.
  • listMarketCatalogue — list markets matching a filter. The primary "what markets are open" query.
  • listMarketBook — current prices for one or more markets. Heavy if polled often.
  • listRunnerBook — like marketBook but at the runner level — sometimes you want one specific selection.
  • listCurrentOrders — your open orders.
  • listClearedOrders — your settled orders, the source of your P&L.
  • placeOrders — the bet-placement call.
  • cancelOrders — cancel unmatched orders.
  • replaceOrders — change the price of an unmatched order without cancelling and re-placing.
  • updateOrders — change the persistence (LAPSE / PERSIST) of an order.

For live price feeds, the streaming API is a separate connection — see the next section.

Streaming vs polling

You can read prices two ways. Polling calls listMarketBook on a timer; streaming opens a persistent connection and receives push updates whenever a price changes.

Polling is easier to start with — you write a loop, fire the call once a second, parse the response. Fine for prototyping. But the rate limits will bite quickly if you're watching more than a handful of markets, and the data is up to a full second stale at any moment. Streaming pushes the diffs as they happen, with sub-100ms latency to the data centre, and has no equivalent rate limit (you pay per connection, not per update). Every production bot uses streaming.

The Python SDK's streaming module is betfairlightweight.streaming; the equivalent flumine framework wraps streaming + strategy logic at a higher level if you don't want to manage the loop yourself.

Orders in depth — types, persistence, BSP

The placeOrders call has three order types and three persistence types. Knowing them avoids surprise behaviour.

Order types

  • LIMIT — back or lay at a specified price. Standard.
  • LIMIT_ON_CLOSE — places a SP-style bet at market close, but only fills if a specified price is achievable. Use for SP strategies — see Betfair SP explained.
  • MARKET_ON_CLOSE — bet at Betfair Starting Price (BSP), unconditional. Always fills, but at whatever the SP is.

Persistence types

  • LAPSE — order cancels at the off (start of in-play). Default for pre-race scalping.
  • PERSIST — order continues into in-play. Useful for "I want to be matched eventually, even if it takes minutes".
  • MARKET_ON_CLOSE — converts an unmatched LIMIT into MARKET_ON_CLOSE at the off. Fills at SP.

Error handling — what goes wrong and how to react

Common errors and their meanings:

  • INSUFFICIENT_FUNDS — your wallet won't cover the bet. Don't retry without reconciling.
  • BET_TAKEN_OR_LAPSED — the price you targeted moved. Retry at current price (with a sanity check on how far it moved).
  • MARKET_SUSPENDED — Betfair temporarily suspended the market (typically because a goal was scored or a runner was withdrawn). Wait and retry; don't spam.
  • EVENT_INACTIVE — the event has ended. Stop placing bets here.
  • TOO_MANY_REQUESTS — you hit the rate limit. Back off exponentially.
  • INVALID_INPUT_DATA — your request was malformed. Don't retry without fixing.
  • CONNECTION_TIMEOUT / network-level failures — retry with backoff, but log so you can review later.

The two most dangerous error patterns are silently ignoring errors (assuming success when there wasn't any) and infinite-retrying on errors that shouldn't be retried (INVALID_INPUT_DATA in particular). Always inspect the response.

The price of data

The Betfair API has two app-key flavours.

  • Delayed key — free. Prices come back with a 1-second delay. Fine for backtesting and learning. Useless for live trading.
  • Live key — £200 one-off fee. Real-time prices. Required for any production bot.

There's no monthly cost beyond that, and no per-bet data fee. The £200 pays for itself fast if your bot has any edge. If your bot doesn't have an edge, the £200 doesn't matter — stop earlier.

Historical data

For backtesting you'll want historical price data. Betfair sells it (via the data shop) and a handful of third-party vendors aggregate and resell it. Headline points:

  • Betfair PRO data — every market, every tick, downloadable per sport per month. Authoritative but expensive at scale.
  • Compressed JSON archives — monthly bundles of "BSP files" and "PRO files", typically a few GB compressed per sport per month.
  • Self-recording — point your streaming client at live markets, write every update to disk. Cheaper but you can only record going forward.

For a first bot, six months of recorded data on your target sport is plenty. Cover the data side in Betfair data analysis.

Testing without risking money

Three patterns we recommend:

  • Delayed app key + paper trading. Log intended bets to a file rather than placing them. Compare logged decisions against the recorded outcome. Free, slow, honest.
  • Sandboxed live key + £2 stakes. Real bets, real prices, throwaway stake size. The bet might win or lose £2; the bug it surfaces is worth £200. This is how we test new strategies.
  • Replay against historical files. Feed your bot a recorded historical stream as if it were live. Useful for replay debugging.

Going to production

Once your bot has paper-traded successfully over at least 100 trades, the production checklist:

  1. Move from delayed key to live key.
  2. Run the bot from a VPS in London (5–15ms lower latency to Betfair's data centre).
  3. Hard-code per-day, per-market, and per-bet stake caps.
  4. Implement a kill switch — separate process can shut down all open positions.
  5. Log every order request and every response to disk. You will want this when something goes wrong.
  6. Set up basic monitoring (a daily email, a Telegram bot, anything that pings you if the bot is alive and what its P&L is).

When the API is the wrong answer

  • You can't code — use Guardian.
  • You want a ladder UI — use Bet Angel or Geeks Toy.
  • You're matched betting — manual is fine; see matched betting.
  • You're not yet sure you have an edge — paper trade manually first; the API doesn't add value until you have a strategy.

Now build something

Reading about the API doesn't deliver an edge — running it does. The companion piece Building Your First Betfair Bot walks through a complete first project end-to-end, including the favourite-drift strategy and the safety rails. If you'd rather get the conceptual model of automation first, read triggers and rules. The pillar piece at trading software reviews covers where the API fits in the wider tooling landscape.

Four small projects to build after the first call

Concrete next steps if you've completed the getting-started flow and want to keep momentum.

Project 1 — Daily market dump

A scheduled script that, every morning, lists all today's UK racing markets and writes them to a CSV. Total code: ~30 lines. Total value: instant overview of the day, plus a permanent record of what was on offer.

Project 2 — Price tracker

For a chosen market, poll the price every 10 seconds for the hour before the off, write to disk. Plot afterwards. You'll start seeing the late-money patterns that traders rely on intuitively.

Project 3 — Bet-history exporter

Pull your last 90 days of settled bets via listClearedOrders, write to a spreadsheet with columns for sport, market, side, stake, P&L. Suddenly you have data to analyse. Tie back to why a trading diary matters.

Project 4 — Email alert on price threshold

Watch a market. If the favourite drifts beyond a chosen price, email yourself. Useful for swing trades — you can step away from the screen and trust the alert.

Streaming API quirks worth knowing

Three things the docs don't emphasise enough:

  • Initial image vs delta updates. First message after subscribing is the full market state; everything after is just the changes. Your code must merge deltas into the cached state correctly.
  • Heartbeats. If you don't receive any update for ~60 seconds, the connection has stalled. Disconnect and reconnect.
  • Authentication tokens expire. If your bot has been streaming for hours and you call a REST endpoint that fails with 401, refresh the session token and continue.

These quirks have wasted real days of debugging for first-time builders. Plan for them upfront.

Why Python (and the honest alternatives)

Most public Betfair bot work is Python because of betfairlightweight and flumine. But the API is language-agnostic. Honest take by language:

  • Python — easiest start, biggest community, fine performance, all examples in this series use it.
  • Node.js — viable with the betfair npm package. JS ecosystem makes web integration easy.
  • C#/.NET — strong on Windows, several mature libraries, good if you're already in the Microsoft stack.
  • Java — works, libraries exist, no real advantage over Python for this use case.
  • Go — niche but fast. No mainstream Betfair SDK; you'd write the API client yourself.

If you have no preference, use Python. If you already know one of the others, stick with it — the language choice isn't where edge comes from.

Security checklist before going live

  • App key stored in .env, never in git.
  • SSL cert and key on a non-cloud-synced folder.
  • Betfair account two-factor authentication enabled.
  • VPS access via SSH key, not password.
  • Kill-switch endpoint require auth.
  • Logs scrubbed of credentials before sharing.