How to Integrate Any REST API Into Your App: A Beginner's Guide
Integrate a REST API into your app in 5 steps: authenticate, send the request, check the status, handle limits. Python and JavaScript code included.
Quick answer: Every REST API integration follows the same five steps. Read the vendor docs, authenticate, send an HTTP request, check the status code, then handle limits and errors. Free? Yes, the code below is free, and many APIs have a free tier.
To show how limits work in real numbers, this guide uses GitHub's public REST API. GitHub's documentation says unauthenticated requests are limited to 60 per hour, and authenticated users get 5,000 per hour (as of 16 October 2026). The code is adapted from the official MDN, Requests and GitHub documentation, not from a test run by the author.
What do you need before you start?
You need three things: the API's documentation, a credential if the API requires one, and a place to run code. The credential is usually an API key or a token. You get it from the vendor's account or developer settings.
Use this checklist before writing any code:
- The base URL. The address all requests start from, for example
https://api.github.com. - The auth method. Most APIs want a token in an
Authorizationheader. RFC 6749 shows the common "bearer" form:Authorization: Bearer <token>. - The rate limit. Find the requests-per-hour or per-minute number in the docs.
- A safe place for the key. Use an environment variable, not a line of code. More on that below.
- A tool to run code. Python 3 with the Requests library, or a browser console or JavaScript runtime that supports
fetch().
If your goal is only to see API data in a spreadsheet, you may not need an app at all. See How to Pull API Data Into Google Sheets With IMPORTDATA and Apps Script.
How do you integrate a REST API into your app? (Method 1: Python)
Send a GET request with the Requests library, set a timeout, check the status, then read the JSON. This is the shortest path in Python. The Requests quickstart documents each piece used here.
- Make sure the Requests library is installed. The Requests quickstart links to its install instructions, so follow those for your setup.
- Get a token from the API vendor. For GitHub, the docs say to use a personal access token for personal use. The token is optional for this demo, but it raises your limit.
- Save the token in an environment variable called
GITHUB_TOKEN. Do not paste it into the script. - Create a file called
call_api.pyand paste the script below. - Run
python call_api.py.
import os
import time
import requests
BASE_URL = "https://api.github.com"
TOKEN = os.environ.get("GITHUB_TOKEN") # optional; never hard-code a real token
def call_api(path, params=None, retries=3):
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "my-app/0.0.1",
}
if TOKEN:
headers["Authorization"] = f"Bearer {TOKEN}"
for attempt in range(retries + 1):
response = requests.get(
f"{BASE_URL}{path}",
headers=headers,
params=params,
timeout=10, # seconds; without a timeout the program can hang
)
# 429 = too many requests, 503 = service unavailable
if response.status_code in (429, 503) and attempt < retries:
retry_after = response.headers.get("Retry-After", "")
wait = int(retry_after) if retry_after.isdigit() else 2 ** attempt
time.sleep(wait)
continue
response.raise_for_status() # raises on any 4XX or 5XX
return response.json()
if __name__ == "__main__":
issues = call_api("/repos/octocat/Spoon-Knife/issues", params={"per_page": 3})
for issue in issues:
print(issue["number"], issue["title"])
Here is what each part does, based on the docs:
params=builds the query string for you. The Requests docs show it encoding the URL correctly.headers=sets custom headers such asAcceptandAuthorization.timeout=is required in practice. The Requests docs say nearly all production code should use it, because leaving it out can cause a program to hang indefinitely.raise_for_status()turns a 4XX or 5XX response into an exception.response.json()decodes the body. It raises an error if the body is invalid JSON or the response is a 204 with no content.
The Retry-After handling reads whole seconds only. MDN says the header can also be an HTTP date, so a production version should parse both. When the header is missing, the script waits 1, 2, then 4 seconds. That backoff pattern is a common convention, not a GitHub requirement.
Method 2: How do you call a REST API with JavaScript fetch()?
Use fetch(), then check response.ok before reading the body. MDN says fetch() makes a GET request by default and is available as a global function in window and worker contexts.
The most common beginner mistake is skipping the status check. MDN states that fetch() does not reject the promise when the server answers with an error such as 404, so you must check the status yourself.
const BASE_URL = "https://api.github.com";
async function callApi(path, params = {}) {
const url = new URL(`${BASE_URL}${path}`);
url.search = new URLSearchParams(params).toString();
const response = await fetch(url, {
headers: { Accept: "application/vnd.github+json" },
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
return response.json();
}
callApi("/repos/octocat/Spoon-Knife/issues", { per_page: 3 })
.then((issues) => issues.forEach((i) => console.log(i.number, i.title)))
.catch((error) => console.error(error.message));
To send data, use a method such as POST with a JSON body and a Content-Type header. This pattern comes straight from MDN:
const response = await fetch("https://example.org/post", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "example" }),
});
MDN notes you cannot put a body on a GET request. For GET, send data as a query string with URLSearchParams, as the script above does.
Do not put a secret token in browser code. Anything sent to a visitor's browser can be read by that visitor. Keep keys on a server you control and have the browser call your server.
Method 3: How do you test an API with curl before writing code?
Run one curl command first. If it works, you know the URL, headers and token are right, and any later failure is in your code. GitHub's own quickstart uses this pattern.
curl --request GET \
--url "https://api.github.com/repos/octocat/Spoon-Knife/issues" \
--header "Accept: application/vnd.github+json" \
--header "Authorization: Bearer YOUR-TOKEN"
Replace YOUR-TOKEN with your own token. GitHub's docs say that in most cases you can use Authorization: Bearer or Authorization: token, but a JSON web token must use Bearer. GitHub's guidance also says not to pass a personal access token as plain text on the command line, so read it from a secure store where you can.
If you would rather have an AI assistant draft the first version of a script, see How to Write Apps Script With Claude, With No Coding Experience. Check any generated code against the vendor docs before running it.
Which method should you choose?
Choose by where your app runs. Python suits scripts and servers. JavaScript fetch() suits web pages and front-end apps. curl suits quick checks.
| Method | Cost | Difficulty | Limits | Best for |
|---|---|---|---|---|
| Python + Requests | Free library | Easy | Needs Python installed | Scripts, back ends, automation |
JavaScript fetch() | Free, built in | Easy | Browser CORS rules apply; keep secrets server-side | Web pages, front-end apps |
| curl | Free | Easy | One request at a time | Testing a URL and token first |
Each method sends the same HTTP request. Only the syntax changes.
Which HTTP method and status code do you need?
Match the verb to the action, then read the status code before the body. MDN's methods table lists which verbs are safe (read-only) and idempotent (repeating them has the same effect as sending once).
| Method | Typical use | Safe | Idempotent |
|---|---|---|---|
| GET | Read data | Yes | Yes |
| PUT | Replace a record | No | Yes |
| DELETE | Remove a record | No | Yes |
| POST | Create a record | No | No |
| PATCH | Partly update a record | No | No |
This matters for retries. MDN's glossary says a client can safely retry an idempotent request. A blind retry of a POST could create a duplicate.
The MDN status code reference explains the codes you will meet most:
| Code | Meaning | What to do |
|---|---|---|
| 400 | The server cannot or will not process a malformed request | Check your URL, parameters and body |
| 401 | Unauthenticated: the server needs credentials | Check the key or token and the header name |
| 403 | The server knows who you are but refuses access | Check scopes and permissions |
| 404 | Resource or endpoint not found | Check the path; some servers use 404 to hide a resource |
| 405 | Method not supported for that resource | Check the docs for the allowed verbs |
| 429 | Too many requests | Wait for Retry-After, then retry |
What's free and what costs money?
The code and libraries here are free. API pricing varies by vendor, so read the vendor's pricing and limits page. GitHub's numbers show how limits typically differ with and without a credential.
| Item | Free? | Limit (as of 16 October 2026) |
|---|---|---|
| Python Requests library | Free | None |
JavaScript fetch() | Free, built into browsers | None |
| GitHub REST API, no token | Free | 60 requests per hour, tied to your IP address |
| GitHub REST API, personal token | Free | 5,000 requests per hour |
| GitHub apps owned by a GitHub Enterprise Cloud organization | Depends on the organization's plan | 15,000 requests per hour, per GitHub's docs |
GitHub's docs add that rate-limit values can vary from one response to the next, because requests are processed in multiple regions. Use the x-ratelimit-limit, x-ratelimit-remaining and x-ratelimit-reset response headers to pace your calls, not a fixed number in your head.
What can go wrong, and how do you fix it?
Most first-time failures fall into six groups. Start with the status code, because it narrows the cause quickly.
- 401 Unauthorized. The key is missing, expired or sent in the wrong header. Re-check the header name and value. OWASP lists sending tokens in the URL as a weakness, so use a header, not a query parameter.
- 403 Forbidden. Your credential works but lacks permission. GitHub recommends giving tokens only the minimum scopes they need.
- 404 Not Found. The path is wrong, or the resource does not exist. Compare your URL with the docs, character by character.
- 429 Too Many Requests. You hit the rate limit. MDN says a
Retry-Afterheader may say how long to wait. GitHub says primary limit overruns return 403 or 429 withx-ratelimit-remainingat 0, and you should wait until the time inx-ratelimit-reset. - A CORS error in the browser. The API's server did not allow your page's origin. MDN says the server must send the right CORS headers, such as
Access-Control-Allow-Origin, or the browser will not share the response. Move the call to your own server. - A hang or a JSON error. A missing timeout can freeze a script. A
JSONDecodeErrorusually means the body was empty (such as a 204) or not JSON. Check the status before you decode.
Is this allowed?
Using an API's official endpoints with your own credentials is what the vendor intends, but you must follow that vendor's terms. Read them before you build. Do not use an API to get around a limit by rotating keys or accounts, and do not scrape a site's pages when it offers no API for that use.
Handle credentials with care:
- GitHub's guidance says to limit token permissions, set an expiry date, and prefer fine-grained personal access tokens.
- It also says not to push tokens or keys to any repository, even a private one.
- Do not share one personal token with other people. GitHub suggests creating a GitHub App instead.
- Have a plan for a leak: revoke the key, issue a new one and check recent activity.
If your app handles personal data, check the privacy rules that apply to your users. This guide does not cover them.
What's still unclear?
This guide gives a general pattern, and every vendor differs on details. Four gaps matter most.
- Rate-limit signals differ. MDN describes 429 with
Retry-After. GitHub documents 403 or 429 plusx-ratelimit-*headers. Your API may use another scheme, so the code above is a starting point. - Auth is not one thing. A simple key or bearer token covers many APIs. Others require the full OAuth 2.0 flow defined in RFC 6749, which this guide does not walk through.
- Pagination and error formats are vendor-specific. The examples fetch three items. Real integrations often need to page through results, and each API does it differently.
- Write operations need extra care. Retrying a POST can duplicate data. Check whether the vendor offers an idempotency feature.
The code here was assembled from official documentation and was not run by the author. Run it against a test account first.
Last checked: 16 October 2026.
Frequently asked questions
What is the difference between 401 and 403 when calling an API?
MDN says a 401 response means the client is unauthenticated: the server does not know who you are, so you need to send valid credentials. A 403 means the server knows who you are but refuses access. For 401, check your key or token. For 403, check the permissions or scopes granted to that credential.
Why does my browser block an API call that works in curl or Python?
Browsers apply the same-origin policy. MDN explains that a web page can only read responses from another origin if that server sends the right CORS headers, such as Access-Control-Allow-Origin. curl and Python do not enforce this rule. If the API does not allow your origin, call it from your own server instead.
Is it safe to retry a failed API request?
It depends on the method. MDN lists GET, PUT and DELETE as idempotent, meaning repeating them has the same effect as sending them once. POST and PATCH are not guaranteed to be idempotent, so a blind retry could create a duplicate record. Check the vendor docs for an idempotency key option before retrying writes.
How do I keep my API key out of my code?
Read it from an environment variable or a secrets manager instead of typing it into a file. GitHub's documentation says not to push tokens or keys to any repository, even a private one, and recommends scoped tokens with an expiry date. If a key leaks, revoke it and issue a new one.
What does a 429 response mean and what should I do?
MDN defines 429 Too Many Requests as the client sending too many requests in a given time. The server may include a Retry-After header saying how long to wait, as seconds or a date. Stop sending requests, wait that long, then try again. Retrying immediately usually makes the problem worse.
Sources
- Using the Fetch API - Web APIs | MDN, MDN Web Docs (2026-10-16)
- HTTP request methods - MDN Web Docs, MDN Web Docs (2026-10-16)
- Idempotent - Glossary - MDN Web Docs, MDN Web Docs (2026-10-16)
- HTTP response status codes - MDN Web Docs, MDN Web Docs (2026-10-16)
- 429 Too Many Requests - HTTP - MDN Web Docs, MDN Web Docs (2026-10-16)
- Retry-After header - HTTP - MDN Web Docs, MDN Web Docs (2026-10-16)
- Cross-Origin Resource Sharing (CORS) - HTTP, MDN Web Docs (2026-10-16)
- Quickstart - Requests 2.34.2 documentation, Requests documentation (2026-10-16)
- Rate limits for the REST API - GitHub Docs, GitHub Docs (2026-10-16)
- Quickstart for GitHub REST API - GitHub Docs, GitHub Docs (2026-10-16)
- Keeping your API credentials secure - GitHub Docs, GitHub Docs (2026-10-16)
- RFC 6749: The OAuth 2.0 Authorization Framework, IETF / RFC Editor (2012-10-13)
- API2:2023 Broken Authentication - OWASP API Security Top 10, OWASP (2023-01-01)