401 Auth Required when accessing accounts api

HI, I am trying to access the accounts api but get a 401 auth required error. At the moment I have 2-auth enabled on my account and I am able to login through the sessions api and then verify this through the verify api and my json output confirms this with “factor” : “complete” and I get a 201 response

But when I try to access the accounts api I get the 401 error. Would you be able to tell me if you see any obvious errors in my code/if there is anything I am missing?

import requests
import pyotp
import sys

username = user
password = password

# 2-auth key
secret = 2 auth key
# Get current 2-auth code
totp = pyotp.TOTP(secret)
code = totp.now()

url = https://api.smarkets.com/v3/sessions/
data = { ‘password’ : password,
’remember’ : True ,
’username’ : username,

# Get a session token
page = requests.post(url, json=data)

token = page.json()[ ‘token’ ]

# Verify the session token using the 2-auth code to login
url2 = https://api.smarkets.com/v3/sessions/verify/
data2 = { ‘code’ : code,
’token’ : token}

# Login to Smarkets
login = requests.post(url2, json=data2)

account = requests.get( https://api.smarkets.com/v3/accounts/ )


Hi Alistair,

You are not using the authentication header in your request. The code should look as follows:

import requests
import pyotp

headers = {"Content-Type": "application/json"}
data = {"username": <username>, "password": <password>}
response = requests.post("https://api.smarkets.com/v3/sessions/", headers=headers, json=data)
token = response.json()["token"]

data = {"token": f"{token}", "code": pyotp.TOTP(<secret>).now()}
response = requests.post("https://api.smarkets.com/v3/sessions/verify/", headers=headers, json=data)
session_token = response.json()["token"]

headers = {"Authorization": f"Session-Token {session_token}"}
response = requests.get("https://api.smarkets.com/v3/accounts/", headers=headers)
accounts = response.json()

Hope this helps.


1 Like

Hi Isabel,

That’s great, thanks very much for helping me


Hi everyone.

I’ve arrived at this post after being pointed towards it by a helpful forum member. I’m getting close but cant understand what the parameter refers to in the following code. Can anyone help please?

Regards Bd

Sorry - fat fingers. I mean the parameter.


OK I’m confused. I’m trying to type S E C R E T but there is obviously something supressing that particular word !!!