Skip to content
12 min read

How to Connect a Telegram Bot to External APIs Without Writing Server Code

Call any external API from a Telegram bot without a server, TLS setup or dependency installs. JavaScript and Python examples, secret storage, timeouts and a no-code comparison.

The easiest way to connect a Telegram bot to an external API without server code is to host the bot on a platform that already has an HTTP client loaded, so a call is a few lines inside your handler. On NxCreate, axios is preloaded in JavaScript bots and requests is preloaded in Python bots, with no imports, no pip installs, no server and no webhook setup. If you want to avoid code completely, a visual automation tool such as Zapier or Make can call the same API, at the price of per-task billing and a separate tool to maintain.

The short version

How do the options compare?

OptionCode neededCost to startLimit that mattersSource
NxCreate (built-in axios or requests)A few lines in a handlerFree Starter plan, no credit card; Pro $5 a month; Business $15 a month4 s per message on Starter, 12 s on Pro; Python scripts have no os, sys, subprocess, threading or file accessHosting page, Python guide
ZapierNone (visual Zaps)Free: $0 and 100 tasks. Professional: from $19.99 a month and 750 tasksFree is limited to two-step Zaps; webhooks start on Professional; every successful action is a taskPricing, Task usage
MakeNone (scenarios and modules)New users get a free accountTelegram and HTTP modules; plan limits are on Make's pricing pageMake HTTP and Telegram
PipedreamOptional code stepsFree plan is $0 but development only; Startup is $99 a month billed annually or $150 billed monthlyProduction use needs Startup; 10,000 credits included, then $0.012 eachPricing
Telegram ServerlessJavaScript modules and the tgcloud command lineSet up through @BotFatherNode.js 18 or newer locally; no npm packages; the only network access is the SDK's fetchTelegram docs
Your own VPSFull server codeA monthly server billYou configure HTTPS, a domain and the webhook yourselfNxCreate hosting page

How do I call an external API from my bot?

Call it from inside the handler with the preloaded client and reply with the result. There is nothing to install and no server to run.

JavaScript: axios

JavaScript bots on NxCreate are a single Telegraf file, and HTTP calls use the global axios instance. Wrap the call in try/catch so a failing API produces a message instead of a silent crash. Replace YOUR_API_URL with the endpoint you want to call.

javascript
bot.command('news', async (ctx) => {
  try {
    const response = await axios.get('YOUR_API_URL/news');
    await ctx.reply('Latest news: ' + response.data.headline);
  } catch (err) {
    await ctx.reply('The news service is not answering. Try again in a minute.');
  }
});

Sending data works the same way: axios.post() with a JSON body, for example the user id and a message.

Python: requests

A Python bot on NxCreate is a set of command scripts, one per trigger, with requests available for HTTP calls to public URLs. Scripts are plain statements with no function wrapper, no imports and no polling loop. The json module is preloaded as well.

The example uses the standard requests syntax: params adds query-string values and r.json() decodes the body. That documentation also warns that a successful r.json() call does not mean the HTTP response succeeded, so the script checks the status code first. Replace YOUR_API_URL with your endpoint.

python
# command: /price
key = env.get("PRICE_API_KEY")
r = requests.get("YOUR_API_URL/price", params={"symbol": "BTC", "key": key})
if r.status_code == 200:
    data = r.json()
    bot.replyText(u, "BTC: " + str(data["price"]))
else:
    bot.replyText(u, "The price service is not answering. Try again in a minute.")

bot.replyText(u, text) sends the reply to the user who wrote to the bot. If a script crashes, an error script type runs, so you can send a friendly message from one place.

Where do API keys go?

Keys go in private variables, not in the script. On NxCreate you add them under Environment / Private Variables and read them with env.get("KEY_NAME"), which keeps them out of your code and out of any repository you copy the script into.

Zapier makes the same point from the other side: it says keys in self-built scripts often sit in a repo, and that its credentials are managed by Zapier. The rule is the same on any platform: one place for secrets, referenced by name.

What if the API is slow?

Acknowledge the request immediately, then send the result. Botable's guide puts it well: a reply that takes eight seconds with no acknowledgement reads as a failure.

On NxCreate the budget is tighter than that. Scripts get 4 seconds on the free plan and 12 seconds on Pro, and the Python guide says to avoid long loops and time.sleep. For work that needs longer, split it up. Bot.runCommandAfter schedules a delayed command that survives restarts, so a first command can answer "Fetching..." and a second can deliver the result. Business has a custom timeout, per the plan comparison.

How should the bot handle a failing or rate-limited API?

Time out fast, retry at most once for transient errors, then tell the user the source is unavailable. Botable recommends that pattern and notes that serving a stale cached value with a note about its age is often better than an error.

Caching matters more than it looks. Botable's example: a bot with a hundred users asking for the same weather calls the provider a hundred times without it. Its suggested windows are a minute for prices, an hour for weather and a day for reference data. NxCreate gives Python bots Bot.saveData for bot-wide storage, which is enough to hold a cached response and its timestamp.

What about APIs that push data to my bot?

Give the provider something to post to, and verify a shared secret on every incoming request, as Botable advises. On NxCreate, payment confirmations, order updates and monitoring alerts can reach your bot through the managed webhook endpoint, with no server of your own.

Telegram uses the same idea for its own updates. Its Bot API lets you set a secret_token of 1 to 256 characters that Telegram sends in the X-Telegram-Bot-Api-Secret-Token header on every webhook call, and it requires a public HTTPS URL on port 443, 80, 88 or 8443. On NxCreate the webhook is registered for you on deploy, so you do not make that call yourself.

For polling on a schedule, NxCreate's JavaScript runtime has two kinds of timer. setTimeout, setInterval and cron.schedule live only inside the running process and may disappear on reload. persistentCron.schedule and persistentScheduler.setTimeout are stored outside the runtime and survive reloads. Use the persistent ones for a daily report or a reminder that must still fire.

Can a bot call an API that needs OAuth?

Yes, but it is a bigger job than a shared API key. Botable describes it as a materially bigger build: the user has to authorise through a web step outside the chat, and you need to store a token per user. If your API accepts a key or bearer token, start there. If every user must sign in to their own account, a connector platform that manages the OAuth flow can save time. Pipedream, for example, lists managed auth for 3,000+ APIs.

Which option should I pick?

Questions

Do I need to write server code to call an API from a Telegram bot?

  1. You write the handler, not the server. NxCreate registers the webhook on deploy, keeps the bot online, and preloads the HTTP client.

Do I need to install axios or requests?

  1. The bot, db and axios objects are already available in JavaScript bots, and Python scripts are plain statements with no imports.

Can I use python-telegram-bot or aiogram?

Not directly. They run their own polling or webhook loop, while NxCreate calls a separate script for each command. You can port your handlers into command scripts.

How much does it cost?

The Starter plan is free with no credit card. Pro is $5 a month and Business is $15 a month. Per the plan comparison, Pro raises deployments to 50 a day and the timeout to 12 seconds, and Business adds a 99.9% uptime SLA.

Is Zapier or Make easier than writing a handler?

For a simple trigger and action, yes. Make states no code is required and Zapier is visual. A handler is easier once the logic has branches, per-user state or caching, because you keep it in one script next to the bot.

Next steps

  1. Create a bot with @BotFather and add it to NxCreate by following the quickstart.
  2. Paste one of the examples above into a handler and replace the URL with your API.
  3. Add your key as a private variable and read it by name.
  4. Read how the runtime, web requests and persistent schedules work.
  5. Moving an existing pyTelegramBotAPI bot? Follow the telebot hosting guide. For plans and limits, see free Telegram bot hosting.
  6. Need Python specifics? The Python bot hosting guide covers script types, storage and limits.