Skip to main content

HTTP requests (fetch)

The Fetch API allows you to make outbound HTTP requests in Deno Deploy. It is a web standard and has the following interfaces:

  • fetch() - The method that allows you to make outbound HTTP requests
  • Request - represents a request resource of fetch()
  • Response - represents a response resource of fetch()
  • Headers - represents HTTP Headers of requests and responses.

This page shows usage for the fetch() method. You can click above on the other interfaces to learn more about them.

Fetch also supports fetching from file URLs to retrieve static files. For more info on static files, see the filesystem API documentation.

fetch()

The fetch() method initiates a network request to the provided resource and returns a promise that resolves after the response is available.

function fetch(
resource: Request | string,
init?: RequestInit,
): Promise<Response>;

Parameters

nametypeoptionaldescription
resourceRequest
USVString
falseThe resource can either be a request object or a URL string.
initRequestInittrueThe init object lets you apply optional parameters to the request.

The return type of fetch() is a promise that resolves to a Response.

Examples

The Deno Deploy script below makes a fetch() request to the GitHub API for each incoming request, and then returns that response from the handler function.

import { serve } from "https://deno.land/std@0.202.0/http/server.ts";

async function handler(req: Request): Promise<Response> {
const resp = await fetch("https://api.github.com/users/denoland", {
// The init object here has an headers object containing a
// header that indicates what type of response we accept.
// We're not specifying the method field since by default
// fetch makes a GET request.
headers: {
accept: "application/json",
},
});
return new Response(resp.body, {
status: resp.status,
headers: {
"content-type": "application/json",
},
});
}

serve(handler);