Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Standard Library and Web APIs

fetch and the Web APIs

Make HTTP requests in Deno with fetch, build Request and Response objects, work with Headers, JSON, FormData and URLSearchParams, handle errors and timeouts, and need only --allow-net.

In Deno, the way you call an HTTP API is the same code you would write in a browser: fetch. It returns a Response, takes a Request, uses Headers, and reads bodies as JSON, text or streams. These are not Deno inventions but web standards, which means everything you learn here carries over to browsers, service workers and other runtimes.

This lesson covers making requests, building responses, handling errors and timeouts, and sending forms. It is also the foundation for HTTP Servers: a Deno server is a function from Request to Response.

Deno is not available on this site, and the Piston runner has no internet access. The runnable examples use the same web-standard classes under Node.js, and talk to a tiny local server where a network call is needed.

Your first request

TypeScript
const res = await fetch("https://api.example.com/users/1");

console.log(res.status);                   // 200
console.log(res.ok);                       // true for 200-299
console.log(res.headers.get("content-type"));

const user = await res.json();
console.log(user.name);
Terminal
deno run --allow-net=api.example.com main.ts

fetch needs --allow-net. Scoping it to the host you call is good practice (Permissions). The body can be read once, with .json(), .text(), .arrayBuffer(), .blob(), .formData() or .body (a stream). Calling a second reader throws, because the body is a one-time stream; use res.clone() if you need two.

Errors: the status is not an exception

fetch rejects only when the request could not be made at all (no network, DNS failure, aborted). A 404 or 500 is a successful fetch that returned an unhappy response. Always check res.ok:

TypeScript
async function getJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`GET ${url} failed: ${res.status} ${res.statusText}`);
  }
  return await res.json() as T;
}

Sending data

For a JSON body, set the header and stringify:

TypeScript
const res = await fetch("https://api.example.com/users", {
  method: "POST",
  headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
  body: JSON.stringify({ name: "Ada", role: "admin" }),
});

For HTML-form style data use FormData (and fetch sets the right header, including the multipart boundary) or URLSearchParams:

TypeScript
const form = new FormData();
form.set("title", "Report");
form.set("file", new File(["hello"], "hello.txt", { type: "text/plain" }));
await fetch("https://api.example.com/upload", { method: "POST", body: form });

const query = new URLSearchParams({ q: "deno", page: "2" });
await fetch(`https://api.example.com/search?${query}`);

Never build query strings with string concatenation: URLSearchParams and URL encode special characters for you.

Request, Response and Headers in practice

You can create these objects yourself, which is exactly what a server does. The example below needs no network. It builds a request, inspects it and builds a response.

Node.js Request, Response and Headers

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.

Headers is case-insensitive and can hold repeated values. It exposes get, set, append, delete, has and iteration. Response.json(data) is a shortcut that sets the content type for you, and Response.redirect(url, 302) builds a redirect.

A handler is just a function

Every Deno server boils down to "take a Request, return a Response". Because that is plain JavaScript, you can test a handler without any server at all:

Node.js Testing a handler without a network

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.

Talking to a real server

Loopback networking works on the Piston runner, so this example starts a tiny server and calls it with fetch, much like a Deno program calling an API. In Deno you would use Deno.serve instead of http.createServer.

Node.js fetch against a local server

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.

Timeouts, retries and redirects

fetch has no built-in timeout. Add one with a signal (Async Code):

TypeScript
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });

Redirects are followed automatically (redirect: "follow"); use "manual" to inspect them or "error" to forbid them. fetch does not retry; wrap it with retry from @std/async for idempotent GET requests.

Streaming responses

res.body is a ReadableStream of bytes. Use it to avoid loading a huge file into memory, for example to save a download straight to disk:

TypeScript
const res = await fetch("https://example.com/big.zip");
using file = await Deno.open("big.zip", { write: true, create: true });
await res.body!.pipeTo(file.writable);

This needs --allow-net and --allow-write. See URL, Streams and Encoding.

Other web APIs you can use

API Use
URL, URLSearchParams, URLPattern Parse and match addresses
AbortController, AbortSignal Cancel work
Blob, File, FormData Binary data and uploads
TextEncoder, TextDecoder Strings and bytes
ReadableStream, WritableStream, TransformStream Streaming data
crypto, crypto.subtle Random values, hashing, encryption
WebSocket Two-way connections
BroadcastChannel, Worker, MessageChannel Messaging between workers
structuredClone Deep copies
EventTarget, Event, CustomEvent Event systems
performance, setTimeout, queueMicrotask Timing
localStorage Simple key-value storage (persisted per script origin)

Deno also provides navigator.userAgent (for example Deno/2.1.4) and navigator.hardwareConcurrency. A good test for "is this a web API?" is whether the same code would run in a browser console; if so, it works in Deno.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A fetch call returns status 404. What happens?

    fetch only rejects on network-level failures. HTTP error statuses resolve normally, so check res.ok.
  2. 2. Which permission does fetch need?

    Any network request needs --allow-net, ideally scoped to the host.
  3. 3. How do you add a 5 second timeout to a fetch?

    fetch has no timeout option; AbortSignal.timeout provides one.
  4. 4. Why can you read a response body only once?

    The body is a ReadableStream. Use res.clone() before reading if you need it twice.

Summary

  • fetch returns a Response; check res.ok because HTTP errors do not reject.
  • Needs --allow-net, scoped by host.
  • Build requests with JSON.stringify, FormData or URLSearchParams.
  • Request, Response and Headers are plain objects you can create and test directly.
  • Add timeouts with AbortSignal.timeout; stream large bodies with res.body.
  • Anything that works in a browser console probably works in Deno.

Next: URL, Streams and Encoding