Broker API HubMenu

Stage 3 of 4, lesson 16 of 31. Beginner

API keys, demo accounts and how not to leak either

What an API key is, why you start on a demo account, and the one habit that keeps a key out of your code: environment variables.

Independent and unofficialCode run

Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.

You need: Nothing beyond Python. Read this before your first API call.

An API key is a password for a program. Anyone who has it can do whatever the key allows, which on a live account can mean placing trades. Treat it like the keys to your account, because it is.

Three rules. Start on a demo account and stay there until your code has run for weeks without a surprise. Never write a key into a script, a notebook, a screenshot or a chat window: set it as an environment variable on your own machine and let the script read it from there. Never type a key into a website that is not your broker's own. This site has no field that asks for one, and never will.

On Windows, set a variable for the current terminal with: set IG_API_KEY=your-demo-key. On macOS or Linux: export IG_API_KEY=your-demo-key. The script reads it with os.environ, so the key never appears in a file you might share.

The script on this page practises the habit with a made up variable name and no real key. It was run with the variable not set, which is why the last line says so. It also shows how to mention a key in output without showing it, because what a program prints ends up in logs, screenshots and bug reports.

How you get a key differs by broker, and some brokers only issue one to live account holders. The table below is read from this site's register for IG, with the source and the date each line was last checked.

The code

# Read a key from an environment variable and never print it in full.
# No broker, no account, no internet. The name below is an example, not a real setting,
# and the script works with nothing set at all.
import os

NAME = "EXAMPLE_DEMO_API_KEY"


def mask(secret, show=4):
    """Hide all but the last few characters, so a key can be mentioned without being shown."""
    if len(secret) <= show:
        return "*" * len(secret)
    return "*" * (len(secret) - show) + secret[-show:]


print("Masked:", mask("not-a-real-key-1234"))
print("Too short to show any of it:", mask("abc"))

key = os.environ.get(NAME)       # None when the variable is not set. It never raises.
if key is None:
    print(NAME, "is not set. Set it in your terminal, never in this file.")
else:
    print(NAME, "is set:", len(key), "characters,", mask(key))

What you should see

Masked: ***************1234
Too short to show any of it: ***
EXAMPLE_DEMO_API_KEY is not set. Set it in your terminal, never in this file.

Run with Python 3.12 on Windows with the example variable not set. No network, no account and no key.

IG, from the register

How you get a key

API keys are only issued to existing live account holders: generate one in My IG > Settings > API keys.

How to use IG APIchecked

Demo

Partial: demo API works, but no key from a standalone demo account unless it is linked to a live account.

How to use IG APIchecked IG Labs FAQ: the demo and live base addresses, and the demo key rulechecked IG REST trading API guide: examples on the demo hostchecked

Authentication

API key plus username and password returns CST and X-SECURITY-TOKEN, valid 12 hours on a rolling basis with each call resetting the clock on the IG Labs FAQ, while IG's REST trading API guide says 6 hours at first, extended up to a maximum of 72 hours: a disagreement between two IG pages that the blocked reference page could not settle on 23 Sep 2026. The v3 OAuth access token lasts as long as the login response says, with a refresh token that expires later. All tokens are invalidated during weekend maintenance.

Sources conflict IG Labs FAQ: 12 hours between calls, reset by each call. IG Labs REST trading API guide: 6 hours at first, extended up to 72 hours while in use.

IG Labs REST trading API guidechecked IG Labs FAQchecked

The full IG page

Check yourself

Answer each question from the code above before you open it. The answers were written from the script on this page and what it printed.

What does os.environ.get return when the variable has not been set?

None, with no error, which is how the script can print a helpful line. Reading it with square brackets instead would stop the program with a KeyError.

Why is the short value abc hidden completely?

mask shows the last four characters. A value of four characters or fewer would be shown whole, so the function returns only stars for it.

When a key is set, why does the script print its length and a masked form and not the key?

Whatever a program prints can end up in a log file, a screenshot or a message asking for help. The length and the last few characters are enough to tell which key was picked up.

Exercise

Change mask so that it shows the last six characters by default, and run the script again. Is the short value still hidden?

What the changed script prints
Masked: *************y-1234
Too short to show any of it: ***
EXAMPLE_DEMO_API_KEY is not set. Set it in your terminal, never in this file.

Captured from a run of the solution on . Run with Python 3.12 on Windows with the example variable not set. No network, no account and no key.

One solution
# Exercise solution: the lesson script with the one change the exercise asks for.
# Read a key from an environment variable and never print it in full.
# No broker, no account, no internet. The name below is an example, not a real setting,
# and the script works with nothing set at all.
import os

NAME = "EXAMPLE_DEMO_API_KEY"


def mask(secret, show=6):
    """Hide all but the last few characters, so a key can be mentioned without being shown."""
    if len(secret) <= show:
        return "*" * len(secret)
    return "*" * (len(secret) - show) + secret[-show:]


print("Masked:", mask("not-a-real-key-1234"))
print("Too short to show any of it:", mask("abc"))

key = os.environ.get(NAME)       # None when the variable is not set. It never raises.
if key is None:
    print(NAME, "is not set. Set it in your terminal, never in this file.")
else:
    print(NAME, "is set:", len(key), "characters,", mask(key))

Your progress

Next: First API call

Your marks are kept in this browser only, in its local storage. They are not sent anywhere, there is no account, and they will not follow you to another browser or device. To remove them, use Clear my progress on the learning track page, or clear this site's data in your browser's settings. Marking needs JavaScript. With scripts off the track reads the same, without the ticks.

Where this sits in the path

Stage 3 of 4: Talking to a broker. What an API sends back, real requests to a practice API that needs no account, how to keep a key safe, a first read only call on a demo account, and histories that arrive in pages.

  1. Read an API response
  2. First HTTP request
  3. Positions and exposure
  4. Keys and demo accountsYou are here
  5. First API call
  6. Paged results
  7. Follow the next page
  8. Price history to CSV

The whole path, every stage

Back: Positions and exposureNext: First API call