Modern examples of asynchronous requests to REST API (with real code)

If you’re building anything on the web in 2025, you’re probably sending async calls all day long. But most tutorials still show toy snippets instead of real examples of asynchronous requests to REST API examples that look like the code you actually ship. This guide fixes that. We’ll walk through practical, production-style examples of asynchronous requests to REST API endpoints using JavaScript, Python, and modern tooling. You’ll see how async calls behave in the browser, in Node.js, and in backend workers that process long-running tasks. Along the way, you’ll get an example of polling, webhooks, queues, and concurrency limits—the patterns teams actually use when APIs are slow, spiky, or rate-limited. The goal is simple: after reading this, you’ll be able to look at your own codebase and say, “Yes, I know exactly where asynchronous REST requests are happening, why they’re written that way, and how to improve them without breaking production.”
Written by
Jamie
Published

Real-world examples of asynchronous requests to REST API examples

Let’s start with concrete scenarios instead of abstract definitions. When engineers talk about modern examples of asynchronous requests to REST API examples, they’re usually dealing with at least one of these situations:

  • The browser should stay responsive while data loads.
  • A mobile app needs to keep working even on a slow network.
  • A backend service must call multiple APIs in parallel to hit latency targets.
  • A long-running task (like video processing) can’t block a request.

We’ll walk through several real examples, then circle back to patterns you can reuse.


Frontend example of asynchronous requests with fetch and async/await

The most familiar example of asynchronous requests to REST API examples lives in the browser. You click a button, the UI shows a spinner, and JavaScript fires off an HTTP request without freezing the page.

// Load user profile and recent activity in parallel
async function loadDashboard(userId) {
  try {
    const [profileRes, activityRes] = await Promise.all([
      fetch(`/api/users/${userId}`),
      fetch(`/api/users/${userId}/activity?limit=20`)
    ]);

    if (!profileRes.ok || !activityRes.ok) {
      throw new Error('Failed to load dashboard data');
    }

    const [profile, activity] = await Promise.all([
      profileRes.json(),
      activityRes.json()
    ]);

    renderProfile(profile);
    renderActivity(activity);
  } catch (err) {
    console.error(err);
    showError('Could not load dashboard. Please try again.');
  }
}

This is a clean example of asynchronous requests to REST API endpoints used in parallel:

  • The UI doesn’t block while fetch runs.
  • Two REST calls are started at the same time with Promise.all to reduce latency.
  • Errors are handled once, not in every callback.

This pattern scales nicely when you add more endpoints, but you do need to watch out for rate limits and timeouts.


React hook example of async REST calls with cancellation

In 2024–2025, React apps are everywhere, and hooks are the default. A realistic example of asynchronous requests to REST API examples in React includes cancellation, so you don’t update state on an unmounted component.

import { useEffect, useState } from 'react';

export function useUserSearch(query) {
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!query) {
      setResults([]);
      return;
    }

    const controller = new AbortController();
    const { signal } = controller;

    async function fetchResults() {
      setLoading(true);
      setError(null);
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal });
        if (!res.ok) throw new Error('Search failed');
        const data = await res.json();
        setResults(data.items);
      } catch (err) {
        if (err.name !== 'AbortError') {
          setError(err.message);
        }
      } finally {
        setLoading(false);
      }
    }

    fetchResults();

    return () => controller.abort();
  }, [query]);

  return { results, loading, error };
}

This hook illustrates a more production-ready example of asynchronous requests to REST API endpoints:

  • Debatable but common behavior: fetch on every query change.
  • Uses AbortController so outdated requests don’t fight over state.
  • Encapsulates loading and error handling.

In a real app, you’d likely combine this with debouncing so the API doesn’t get hammered on every keystroke.


Node.js example: parallel REST calls in an API gateway

On the backend, examples of asynchronous requests to REST API examples often appear in API gateways or BFFs (backend-for-frontend services). A single client call fans out to several internal or third-party APIs.

// Express-style route handler aggregating multiple REST APIs
app.get('/api/dashboard', async (req, res) => {
  const userId = req.user.id;

  try {
    const [profileRes, billingRes, alertsRes] = await Promise.all([
      fetch(`https://users.internal/api/users/${userId}`),
      fetch(`https://billing.internal/api/accounts/${userId}`),
      fetch(`https://alerts.internal/api/alerts?user=${userId}`)
    ]);

    if (!profileRes.ok || !billingRes.ok || !alertsRes.ok) {
      return res.status(502).json({ error: 'Upstream service failure' });
    }

    const [profile, billing, alerts] = await Promise.all([
      profileRes.json(),
      billingRes.json(),
      alertsRes.json()
    ]);

    res.json({ profile, billing, alerts });
  } catch (err) {
    console.error('Dashboard error', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

This is one of the best examples of asynchronous requests to REST API services working together:

  • The gateway hides internal complexity from the client.
  • Multiple async REST calls run concurrently to keep latency low.
  • Failures are normalized into a single HTTP response.

In real systems, you’d add retries, circuit breakers, and structured logging. Libraries like p-limit help throttle concurrency so you don’t overload dependencies.


Python asyncio example of high-throughput REST calls

Python’s asyncio stack matured significantly, and by 2025 it’s common in high-throughput microservices. Here’s a Python example of asynchronous requests to REST API endpoints using aiohttp.

import asyncio
import aiohttp

API_BASE = "https://api.example.com"

async def fetch_user(session, user_id):
    async with session.get(f"{API_BASE}/users/{user_id}") as resp:
        resp.raise_for_status()
        return await resp.json()

async def fetch_many_users(user_ids):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_user(session, uid) for uid in user_ids]
        return await asyncio.gather(*tasks, return_exceptions=True)

async def main():
    user_ids = range(1, 101)
    results = await fetch_many_users(user_ids)

    successes = [r for r in results if not isinstance(r, Exception)]
    failures = [r for r in results if isinstance(r, Exception)]

    print(f"Fetched {len(successes)} users, {len(failures)} failed")

if __name__ == "__main__":
    asyncio.run(main())

This async pattern is common in data pipelines and internal tools that need to call REST APIs for hundreds or thousands of entities. It’s a realistic example of asynchronous requests to REST API examples where throughput matters more than single-request latency.

For production, you’d wrap this with concurrency limits using asyncio.Semaphore to avoid overwhelming the remote service.


Long-running jobs: async REST with polling

Sometimes an API can’t finish the job during a single request. Think video encoding, large report generation, or ML inference. Public APIs from cloud providers often use a submit + poll pattern.

Here’s a JavaScript example of asynchronous requests to REST API endpoints using polling for job status:

// Submit a long-running job
async function startReport(params) {
  const res = await fetch('/api/reports', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params)
  });

  if (!res.ok) throw new Error('Failed to start report');
  const { jobId } = await res.json();
  return jobId;
}

// Poll job status until done or timeout
async function waitForReport(jobId, { intervalMs = 3000, timeoutMs = 600000 } = {}) {
  const start = Date.now();

  while (true) {
    if (Date.now() - start > timeoutMs) {
      throw new Error('Report generation timed out');
    }

    const res = await fetch(`/api/reports/${jobId}/status`);
    if (!res.ok) throw new Error('Status check failed');

    const status = await res.json();

    if (status.state === 'completed') return status;
    if (status.state === 'failed') throw new Error('Report failed');

    await new Promise(r => setTimeout(r, intervalMs));
  }
}

This pattern is everywhere in 2024–2025 cloud APIs. It’s a textbook example of asynchronous requests to REST API examples where the server does heavy work in the background and the client checks in periodically.

For more background on long-running operations and polling patterns, Google’s API design guide is still a solid reference: https://cloud.google.com/apis/design


Webhook-based example: async REST without polling

Polling works, but it’s wasteful. Many modern platforms (Stripe, GitHub, Slack) prefer webhooks: your system exposes a REST endpoint, and their system calls you back when the job is done.

Here’s an example of asynchronous requests to REST API flows using webhooks in Node.js/Express:

// 1) You call the provider asynchronously to start a job
async function startPayment(amount, customerId) {
  const res = await fetch('https://payments.example.com/api/charges', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ amount, customerId, callbackUrl: 'https://yourapp.com/webhooks/payment' })
  });

  if (!res.ok) throw new Error('Payment start failed');
  return res.json(); // contains chargeId, status=pending
}

// 2) They call you back later via a webhook
app.post('/webhooks/payment', express.json(), (req, res) => {
  const event = req.body;

  // Verify signature, then update your DB
  updatePaymentStatus(event.chargeId, event.status)
    .then(() => res.status(200).end())
    .catch(err => {
      console.error('Webhook handling failed', err);
      res.status(500).end();
    });
});

This is a different style of example of asynchronous requests to REST API interactions:

  • You initiate the workflow with a REST call.
  • The provider notifies you via another REST call later.
  • No need for constant polling.

Stripe’s docs remain a good reference for webhook patterns: https://stripe.com/docs/webhooks


Queue-based example: async REST inside microservices

In microservice architectures, REST calls often trigger internal asynchronous workflows via message queues. A REST request comes in, a job is queued, and another worker service processes it later.

Here’s a stripped-down but realistic example of asynchronous requests to REST API examples using a queue (RabbitMQ-style pseudo-code):

// API service: accept upload request and enqueue work
app.post('/api/uploads', async (req, res) => {
  const { fileId, userId } = req.body;

  const job = { fileId, userId, createdAt: Date.now() };
  await queue.publish('file-processing', job);

  // Respond immediately; processing is async
  res.status(202).json({ status: 'queued', fileId });
});

// Worker service: consumes jobs and calls another REST API
queue.subscribe('file-processing', async (job) => {
  try {
    const res = await fetch(`https://virus-scan.internal/api/scan`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ fileId: job.fileId })
    });

    if (!res.ok) throw new Error('Scan failed');
    const result = await res.json();
    await saveScanResult(job.fileId, result);
  } catch (err) {
    console.error('Processing failed for job', job, err);
    await markJobFailed(job, err);
  }
});

This pattern appears in many of the best examples of asynchronous requests to REST API integrations within enterprises:

  • The API stays fast by offloading heavy work.
  • The worker can retry failures without the client waiting.
  • Backpressure is controlled via the queue.

Rate limits and concurrency: async doesn’t mean “firehose”

By 2025, most public APIs enforce strict rate limits. Good examples of asynchronous requests to REST API usage include concurrency control to avoid getting blocked.

Here’s a Node.js example using a simple pool:

import pLimit from 'p-limit';

const limit = pLimit(5); // at most 5 concurrent requests

async function fetchWithLimit(urls) {
  const tasks = urls.map(url =>
    limit(async () => {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`Failed for ${url}`);
      return res.json();
    })
  );

  return Promise.all(tasks);
}

This pattern is especially important when calling health or research APIs, such as those provided by the U.S. National Library of Medicine at https://www.ncbi.nlm.nih.gov or NIH at https://www.nih.gov. They often publish rate limit guidelines, and responsible async design respects those.


Observability: treating async REST as first-class behavior

The last piece that separates toy snippets from real examples of asynchronous requests to REST API examples is observability:

  • Structured logs that tie together a client request ID with every downstream async REST call.
  • Metrics on latency, error rates, and time spent waiting on external APIs.
  • Tracing across services, so a single user action can be followed through all asynchronous requests.

OpenTelemetry (https://opentelemetry.io) has become the default stack for this. If you’re making heavy use of asynchronous REST calls, wiring traces through your HTTP clients is no longer optional if you care about debugging production incidents.


FAQ: common questions about async REST patterns

What are some practical examples of asynchronous requests to REST API usage in a single-page app?

A typical single-page app makes asynchronous requests to REST API endpoints to fetch user data, notifications, and feature flags in parallel when the app loads. It may then send additional async calls for search, autosave, and analytics events while keeping the UI responsive. The React hook example above is a realistic example of how those calls are structured with cancellation and error handling.

Can you give an example of asynchronous requests to REST API patterns for long-running jobs?

Yes. A classic example of asynchronous requests to REST API examples for long-running jobs is report generation: the client sends a POST /reports request, gets back a jobId, and then either polls GET /reports/{jobId} or receives a webhook when the report is ready. The long-running work happens in a background worker, not in the original HTTP request.

How do microservices typically use asynchronous REST calls internally?

Microservices often combine REST with message queues. An incoming REST call enqueues work, and a worker service later calls other internal REST APIs as part of processing. This queue-based pattern is one of the best examples of asynchronous requests to REST API interactions that lets teams scale independently while keeping user-facing endpoints fast.

Are async REST calls always better than synchronous ones?

Not always. Asynchronous requests to REST API endpoints shine when you need concurrency, non-blocking behavior, or long-running work. For simple, quick operations, a straightforward synchronous call is easier to reason about and debug. The sweet spot is usually: keep your external interface predictable, and use async patterns internally to meet performance and reliability goals.

Where can I find more examples of API patterns and best practices?

For design patterns around long-running operations and async workflows, Google’s API design guide is useful. For health and research data APIs, the U.S. National Library of Medicine (https://www.nlm.nih.gov) and NIH (https://www.nih.gov) provide documentation and example usage patterns. These sources help you see how large organizations structure their own examples of asynchronous requests to REST API integrations at scale.

Explore More REST API Examples

Discover more examples and insights in this category.

View All REST API Examples