Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Bot Concepts and APIs

HTTP and JSON for Bot APIs

Learn the HTTP skills every bot needs - methods, headers, JSON bodies, status codes, timeouts with AbortSignal, 429 rate-limit handling and retries with backoff - with runnable fetch examples.

Under every Discord or Telegram library is the same plain technology: HTTP requests carrying JSON. If you understand what a library sends and receives, you can debug any problem, call API features the library does not wrap yet, and decide whether you need a library at all. This lesson covers the HTTP knowledge a bot developer uses daily, using Node's built-in fetch.

Requests, responses and JSON

An HTTP request has a method (GET reads, POST creates or performs an action, PUT replaces, PATCH changes part, DELETE removes), a URL, headers and an optional body. A response has a status code, headers and a body. For bot APIs the body is nearly always JSON, so you set content-type: application/json on requests, send JSON.stringify(object), and read replies with await response.json().

Node.js A JSON round trip with fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

response.ok is true for any status from 200 to 299. Note that fetch does not throw for 404 or 500: it only throws when the network fails. You must check ok (or the status) yourself, and that is why a wrapper function is worth writing once.

Status codes you will meet

Status Meaning for a bot
200, 201, 204 Success (204 has no body: do not call .json())
400 Your request is malformed or breaks a rule (message too long, bad parameter)
401 Token missing or wrong
403 Token is valid but the bot lacks permission (Discord: missing permission or access)
404 The chat, channel or message does not exist, or the bot cannot see it
409 Telegram: conflict, for example two programs polling the same bot
429 You are sending too fast: wait and retry
500, 502, 503 The platform has a problem: retry later

Only some failures are worth retrying. 4xx errors (except 429) are your fault, and repeating the same request gives the same error. 5xx errors and network failures are usually temporary, so a retry makes sense.

Timeouts

fetch has no timeout by default. A hung connection can freeze your polling loop forever. Use AbortSignal.timeout(ms):

Node.js Timeouts with AbortSignal.timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The error name is TimeoutError for a timeout and AbortError for a manual controller.abort(). When you use long polling (Telegram getUpdates with timeout=30), your client timeout must be longer than the server wait, for example 40 seconds.

Rate limits: handling 429

Both platforms limit how fast you can call them. When you exceed a limit you get 429 Too Many Requests and a wait time: Telegram puts parameters.retry_after (seconds) in the JSON body, Discord sends a Retry-After header and retry_after in the body. The right reaction is to wait that long and try again, not to hammer the API.

A reusable request wrapper

Here is a wrapper with the features you want in every bot: JSON in and out, a timeout, errors with context, and retries for 429 and 5xx with exponential backoff and jitter. The stand-in server answers 429 once and 503 once before succeeding.

Node.js A wrapper with retries and backoff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first request survived a 429 and a 503 without the caller noticing. The 403 on /forbidden was not retried: it is a permission problem, and waiting will not fix it. In your real wrapper you would read the platform's exact fields, and you would log failures with enough context (method, path, status) to debug at 3 a.m.

Never retry forever and never retry non-idempotent calls blindly. If a sendMessage request timed out, the message may already have been delivered, and a retry sends a duplicate. For important actions, record that you attempted them, or use an API that supports idempotency.

JSON pitfalls

  • Big numbers. Discord ids are strings for a reason. Never Number() a snowflake.
  • Non-JSON bodies. Proxies and outages return HTML error pages. Use .json().catch(() => null) or read .text() first when the status is not 2xx.
  • Escaping. JSON.stringify escapes quotes and newlines for you. Never build JSON by string concatenation.
  • Undefined fields. JSON.stringify drops properties set to undefined, which is handy for optional parameters but can hide typos.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Does fetch throw an error when the server answers 404?

    fetch resolves for any HTTP status. Only network-level failures reject the promise.
  2. 2. Which failures are worth retrying?

    429 and 5xx are temporary. The 4xx errors describe a problem with your request or permissions, which a retry cannot fix.
  3. 3. How do you give a fetch call a timeout?

    fetch has no timeout option. AbortSignal.timeout(ms) aborts the request after the given milliseconds.
  4. 4. Why can retrying a timed-out sendMessage be dangerous?

    The first request may have succeeded before the connection timed out, so a retry creates a duplicate.

Summary

  • Bot APIs are HTTP with JSON bodies; set content-type and use JSON.stringify and response.json().
  • fetch does not throw for error statuses: check response.ok.
  • Use AbortSignal.timeout on every request; make polling timeouts longer than the server wait.
  • Handle 429 by waiting for the advertised time, retry 5xx with exponential backoff, never retry other 4xx.
  • Wrap all of it in one function so every call behaves the same.

Next: Telegram Updates and Methods