Portfolio Supported AIs Solutions Tasks Email Archive Integrations Pricing

Get Started

ChatGPT

ChatGPT

Start directly →

Ready
Claude

Claude

Directory Connector →

Ready
Mistral

Mistral

Directory Connector →

Ready

Dashboard Always available
← All articles

connect custom api website

Connect a Custom API in 6 Steps, From Discovery to Verified Access

Connect a custom API in six steps: credentials, testing, proxy setup and monitoring. See how the WebsitePublisher API Proxy keeps keys server-side.

The safest way to connect a custom API to your website is a server-side proxy: your backend holds the credentials and makes the call, then your frontend reads the result. Reserve direct browser fetch calls for public, CORS-enabled, read-only endpoints. Before writing any integration code, identify the auth type (usually an API key or Bearer token), send one small validation request to confirm reachability, then set up monitoring so you catch failures early.


TL;DR:

  • Send a small, read-only health request before building UI logic, and keep credentials in server-side environment variables or a managed connector.
  • Use browser fetch only for public, read-only endpoints that allow your origin; credentialed requests require a specific allowed origin, not a wildcard.
  • Check response.ok (fetch() still resolves on HTTP errors like 404 or 500), distinguish 4xx from 5xx, and honor the retry delay on 429 responses.
  • For changing lists, prefer cursor pagination over offsets, request only needed fields, and stop when the API returns no next cursor.
  • Pin each integration to a specific API version, review provider changelogs before upgrades, and validate changed response fields before deploying.

Table of Contents

How to connect a custom API to your website: 6-step checklist

Connecting a custom API is a sequence, not a single step. Working through it in order keeps you from discovering a missing credential or a CORS block halfway through a build.

  1. Record the API’s base URL, the specific endpoints you need, and any required query parameters.
  2. Identify the auth method (API key, Bearer token, OAuth, or Basic auth) and decide whether calls run server-side or client-side.
  3. Send a small validation or health request, a safe GET with no side effects, to confirm the API responds and your credentials work.
  4. Store credentials server-side using environment variables or a managed connector rather than hardcoding them.
  5. Build the request handling logic and map the response fields to your UI or data model.
  6. Turn on monitoring and alerts so failed requests or slow responses surface before customers notice.

Each step depends on the one before it. Skipping the validation request is the shortcut that usually costs the most time later, because an auth problem that would take two minutes to catch early can take hours to diagnose once it is buried inside your UI code.

Authentication and secure credential management

Most custom APIs use one of three auth patterns. An API key is a static string sent as a header or query parameter, common for simpler services. Bearer tokens, often issued through OAuth, expire and need periodic refreshing. Basic auth, a username and password encoded in the request header, shows up on older or internal systems.

  • Never commit API keys, tokens, or passwords to your codebase, even in a private repository.
  • Store credentials in environment variables on your server or inside a managed connector that injects them at request time.
  • For OAuth, build the refresh flow server-side so expired tokens renew automatically without breaking the user’s session.
  • Apply least-privilege scopes: request only the permissions your integration actually uses, and rotate keys on a regular schedule.

Pro Tip: Test your validation request with a scoped, read-only credential first. If that works, you know your auth setup is correct before you ever touch write operations.

Backend proxy vs. browser fetch: which pattern to choose

The right pattern depends on what the API exposes and who can see the credential.

  • A backend proxy, whether a serverless function or a middleware layer, keeps secrets off the client and gives you one place to handle retries and rate limits.
  • Browser fetch calls are reasonable only for public, read-only endpoints that already allow cross-origin requests and require no secret key.
  • Route any response transformation, like reshaping JSON into the fields your frontend expects, through the proxy layer rather than duplicating that logic in multiple frontend components.
  • A proxy also gives you a single point to log errors, which matters once you have more than one page calling the same API.

Making requests from the browser: fetch, CORS, and common pitfalls

When an endpoint is public and CORS-enabled, the Fetch API is the standard way to call it from client-side JavaScript. A basic call looks like fetch(url).then(response => ...), but the Fetch API returns a resolved promise even for 404 or 500 responses, so you always check response.ok before parsing the body.

CORS requires the server to explicitly allow your origin. The Fetch API documentation notes that when a request includes credentials, the server’s Access-Control-Allow-Origin header cannot be set to a wildcard; it must echo your specific origin and include Access-Control-Allow-Credentials. That single rule explains most “it works in Postman but not in the browser” problems.

Test CORS behavior with curl -i -H "Origin: https://your-site.com" against the endpoint (many servers only send CORS headers when an Origin header is present), or inspect the network tab in your browser’s dev tools, to see which headers the server actually sends before you assume your fetch code is broken.

Error handling, rate limits, and resilient patterns

Fetch promises reject only on network-level failures (including CORS blocks and aborted requests), never on HTTP error codes, so checking response.ok on every call is not optional. Treat 4xx and 5xx responses explicitly instead of assuming a resolved promise means success.

  • Check response.ok and branch your error handling for 4xx versus 5xx responses.
  • On a 429 Too Many Requests response, honor the Retry-After header when present, and fall back to exponential backoff with jitter when it is not.
  • Validate the shape of the response before using it, and log schema mismatches instead of letting a malformed field break your UI silently.
  • Set up alerts for error-rate spikes so a provider outage or a quota change gets noticed within minutes, not days.

The OWASP API Security Project lists Unrestricted Resource Consumption (API4:2023) in its API Security Top 10, which is one more reason rate-limit handling belongs in your integration from day one rather than as an afterthought.

WebsitePublisher: how our platform simplifies custom API connections

The built-in API Proxy integration gives you that server-side proxy without writing it from scratch. You register the target URL, choose the auth method (Bearer token, API key header, custom header, or query parameter), and reference a key you stored yourself in the project Vault in the dashboard. Your AI assistant can set this up through the WebsitePublisher connector, and your published pages call the proxy instead of the third-party API, so CORS blocks and exposed keys stop being a problem.

  • Credentials live in the Vault and are attached server-side to each proxied request, never exposed in the browser or the chat.
  • The endpoint list shows whether each proxy has its key in place, so a missing credential is visible before you map response fields.
  • Allowed methods and a rate limit per visitor are set on the proxy itself, so quota rules live in one place.
  • See how this fits the AI web platform, or check supported AI platforms if you are building through a specific assistant.

API versioning and backward compatibility considerations

APIs change over time, and a version bump can silently break your integration if you are not watching for it. Most providers signal versions one of three ways: a path segment like /v2/, a custom header such as API-Version, or a query parameter.

Pin your integration to a specific version rather than always pulling the latest, even if that means missing a new field until you choose to upgrade. Pinning gives you control over when a breaking change hits your site, instead of finding out when a field you depend on suddenly disappears from the response.

When you do upgrade, read the changelog for renamed fields, removed endpoints, and altered response shapes before touching your code. A response validation step, the same one you use for your health check, is useful here too: run your old parsing logic against the new version’s sample responses and see what breaks before you ship the change.

Backward compatibility cuts both ways. If you are building the API as well as consuming it, add new fields without removing old ones, and deprecate endpoints with a clear timeline rather than pulling them without notice. For a third-party API you only consume, the practical move is simpler: check the provider’s deprecation policy, subscribe to their changelog or status page if one exists, and budget time twice a year to review whether your integration still matches the current version.

Pagination and filtering for retrieving large data sets

Most APIs that return lists cap the number of records in a single response, often somewhere between 20 and 100 items by default, and expect you to page through the rest. The two common pagination styles are offset-based, using page and limit or offset and limit parameters, and cursor-based, where the response includes a token you pass back to get the next batch.

Cursor-based pagination tends to hold up better under frequently changing data, since offset pagination can skip or repeat records when items are added or deleted between requests. Check which style the API documentation describes before you write your loop, since the two require different logic.

Filtering parameters, like date ranges, status fields, or search terms, reduce how much data you pull in the first place. Requesting only the fields and records you actually need cuts response size, speeds up parsing, and reduces how often you hit rate limits.

Build your pagination loop to stop on an empty page or a missing cursor rather than assuming a fixed number of pages, since the total record count can change between your first and last request. Cache paginated results when the underlying data does not change often, so you are not re-fetching the same records on every page load.

Pagination and filtering for retrieving large data sets — overview diagram

Webhook integration and handling for real-time updates

A webhook flips the usual request pattern: instead of your site polling the API for updates, the API calls a URL you provide whenever an event happens. This is the standard approach for real-time updates like payment confirmations, form submissions, or status changes, because it avoids the delay and wasted requests of constant polling.

To receive webhooks, you need a public endpoint that accepts POST requests and responds quickly, typically within a few seconds, even if your actual processing takes longer. A common pattern is to acknowledge the webhook immediately with a 200 response, then queue the actual work to run afterward, so a slow database write does not cause the provider to think the webhook failed and retry it.

Webhook delivery, acknowledgment, and queued processing

Verify webhook authenticity using the signature header most providers include, usually a hash computed from a shared secret and the payload. Skipping this check means anyone who finds your webhook URL could send fake events. Compare signatures with a constant-time function, and reject events whose timestamp is more than a few minutes old to block replay attacks.

Plan for duplicate deliveries. Providers often retry a webhook if your endpoint does not respond fast enough or returns an error, so your handler should be idempotent, meaning it produces the same result whether it processes an event once or three times. A unique event ID in the payload, checked against records you have already processed, handles this cleanly.

For a worked example with real payment events, see our Stripe integration guide, which covers webhook endpoints and signature checks.

Best practices for API documentation and using OpenAPI/Swagger

Good API documentation answers three questions before you write a line of code: what endpoints exist, what authentication they require, and what a successful response looks like. If you are integrating with an API that provides an OpenAPI or Swagger specification, that file gives you all three in a format tools can read directly, which means less manual guesswork about field names and required parameters.

An OpenAPI spec also lets you generate a client library or import the API straight into a tool like Postman or Insomnia, so you can send real test requests before writing integration code. That matches the validation-request habit from earlier in this guide: run a few calls against the spec’s documented endpoints, confirm the real responses match what the spec promises, and only then start building your mapping logic.

If you are the one publishing the API, keep the documentation next to the code that implements it, and update both together. A spec that drifts from the actual behavior of the API is worse than no spec at all, because it sends the next integrator down the wrong path with false confidence. Include example requests and example responses for every endpoint, not just a list of parameter names, since examples are what most developers actually copy from when they start building.

Security best practices beyond authentication

Authentication confirms who is calling your API, but it does not cover everything that keeps an integration safe. Enforce HTTPS on every request, both to the API you are calling and on any proxy endpoint you build, since credentials and data sent over plain HTTP can be intercepted on the network.

Validate and sanitize every field you receive before you use it in your own database queries or render it in your UI. The OWASP API Security Project lists unsafe consumption of API responses as a recognized risk category, which means trusting a third-party API’s output without validation can introduce vulnerabilities into your own site even when the API itself is secure.

Set reasonable timeouts on every outbound request so a slow or hanging API does not tie up your server resources. Log request and response metadata, not full payloads containing sensitive data, so you can debug issues without creating a security liability in your own logs. Finally, restrict your proxy endpoint so it only accepts requests from your own frontend, using an origin check or a shared internal token, rather than leaving it open as an unauthenticated public API in its own right. Origin headers can be faked outside a browser, so add rate limiting to the proxy as well.

Common mistakes and quick fixes

Three mistakes come up again and again. Keys exposed in client-side bundles get fixed by rotating the key and moving the call server-side. Misconfigured CORS headers that return opaque, unreadable errors get fixed by correcting the server’s Access-Control-Allow-Origin value and testing with curl. Missing 429 handling gets fixed by honoring Retry-After and adding exponential backoff.

Speed up your next integration with WebsitePublisher

Connecting a custom API the careful way, proxying credentials, validating the connection, handling retries, takes real setup time when you build it from scratch every time. We shortened that path with the built-in API Proxy: register the target URL and auth method once, keep the key in the Vault, and every page on your site can call it. Your AI assistant handles the setup through the WebsitePublisher connector.

Websitepublisher

If you want to see how this fits into a full site or app build, visit the AI web platform page, or go straight to plans and pricing to pick the tier that matches your project (API Proxy endpoints need a Starter plan or higher).

FAQ

How do I connect an API to a website?

Record the base URL and endpoints, choose an auth method like an API key or Bearer token, then send a small validation request to confirm the connection works. From there, decide whether to call the API from a server-side proxy or directly from the browser, depending on whether the endpoint is public and CORS-enabled.

Can I create an API for any website?

You can build a custom API for most websites you control, since an API is just a defined set of endpoints your server exposes for other programs to call. Whether it makes sense depends on your site’s backend setup; a static site with no server logic needs a separate backend or a managed connector before it can expose one.

Are there free APIs I can connect to my website?

Many public APIs offer a free tier for testing or low-volume use, though terms vary by provider and are not universal. Check the specific API’s documentation for its current free-tier limits before building against it.

What is an API-connected website?

An API-connected website is one that pulls data or functionality from an external service, like a payments processor or a mapping provider, through defined requests rather than hardcoding that information into the page. The connection typically uses authentication like an API key or Bearer token and returns data in a format such as JSON for the site to display or act on.

Why does my API call work in Postman but fail in the browser?

Postman doesn’t enforce CORS, but browsers do. If the API server doesn’t return an Access-Control-Allow-Origin header that matches your site’s origin, the browser blocks the response even though the request reached the server. Ask the provider to allow your origin, or route the call through a server-side proxy.

Is it safe to put an API key in frontend JavaScript?

No. Anything shipped to the browser, including environment variables bundled at build time, can be read by any visitor. Keep keys on the server and call the API through a proxy or managed connector.

Sources

Build your site the same way

Describe what you want. Your AI builds and publishes it — with the full stack behind it: data, auth, forms, payments, integrations and hosting.

See how it works →