Code2FA
EN
EnglishTiếng Việt中文РусскийEspañol

Get 2FA codes with an API or in code

Code2FA team · Updated · 2 min read

Quick answer

In scripts, computing TOTP locally is safest (Python: pyotp.TOTP("KEY").now(); Node: otplib). If you need an API, Code2FA offers GET https://api.code2fa.co/tok/KEY returning {"token":"123456"} like 2fa.live, but the key travels over the network.

Get 2FA codes with an API or in code

When a script or automation needs a 2FA code, you can either compute the code in your own code or call an API that returns it. The first is safer.

Option 1: compute the code yourself (recommended)

TOTP is an open standard (RFC 6238) with libraries in every language. The key never leaves your machine.

# Python: pip install pyotp
import pyotp
print(pyotp.TOTP("JBSWY3DPEHPK3PXP").now())
// Node.js: npm i otplib
import { authenticator } from "otplib";
console.log(authenticator.generate("JBSWY3DPEHPK3PXP"));

Code2FA's zero-dependency TOTP engine (with Steam Guard and Google Authenticator export QR parsing) is open source on GitHub: nguyennoben-a11y/code2fa-totp.

Option 2: call an API

Code2FA offers a free API in the same format as 2fa.live:

curl https://api.code2fa.co/tok/JBSWY3DPEHPK3PXP
# {"token":"123456"}
  • GET /totp/KEY?digits=8&period=30&algorithm=SHA256: advanced options, Steam type.
  • POST /bulk: one key per line, up to 500.
  • GET /time: server time to check clock drift.

Details in the API docs.

Trade-offs of using an API

  • Calling an API means the key travels over the network in the URL and can end up in proxy logs or history. That applies to every API, including Code2FA's.
  • Use APIs for low-value keys or when you can't install a library. For important accounts, compute codes locally.
  • Keep the script machine's clock synced (NTP) or codes will be wrong. See rejected 2FA codes.
Only automate 2FA for accounts you own or are allowed to manage. Where a service has an official API (GitHub, Google Cloud…), use its tokens or API keys instead of automating 2FA entry.

FAQ

Is there a free API to get 2FA codes?

Yes. Code2FA offers GET https://api.code2fa.co/tok/KEY returning {"token":"123456"}, compatible with 2fa.live. Computing codes locally with pyotp/otplib is safer, though.

How do I get a 2FA code from a key in Python?

Install pyotp and call pyotp.TOTP("KEY").now().

Related articles