0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Fetch in Deno: Simple Guide with Examples

In Deno, you use the fetch function to make HTTP requests just like in browsers. It returns a promise that resolves to a response object, which you can read using methods like response.text() or response.json().
๐Ÿ“

Syntax

The fetch function takes a URL string or a Request object as its first argument. It returns a promise that resolves to a Response object. You can optionally pass a second argument with options like method, headers, and body.

  • url: The address to request.
  • options: An object to customize the request (method, headers, body).
  • Response: The result containing status, headers, and body methods.
typescript
const response = await fetch(url, {
  method: 'GET',
  headers: { 'Content-Type': 'application/json' }
});
const data = await response.json();
๐Ÿ’ป

Example

This example fetches JSON data from a public API and logs the title of the first post. It shows how to await the response and parse JSON.

typescript
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
  console.error('HTTP error', response.status);
} else {
  const post = await response.json();
  console.log('Post title:', post.title);
}
Output
Post title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
โš ๏ธ

Common Pitfalls

Common mistakes include forgetting to await the fetch call or response parsing, not checking response.ok for errors, and trying to read the body multiple times.

Also, Deno requires explicit permissions to access the network, so run your script with --allow-net flag.

typescript
/* Wrong: Missing await and error check */
const response = fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = response.json(); // Error: response is a Promise

/* Right: Await and check response */
const responseCorrect = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (responseCorrect.ok) {
  const dataCorrect = await responseCorrect.json();
  console.log(dataCorrect);
}
๐Ÿ“Š

Quick Reference

FeatureDescription
fetch(url, options?)Make HTTP request, returns Promise
response.okTrue if status is 200-299
response.statusHTTP status code
response.json()Parse response body as JSON
response.text()Parse response body as plain text
--allow-netDeno flag to allow network access
โœ…

Key Takeaways

Use await fetch(url) to make HTTP requests in Deno.
Always check response.ok before reading the response body.
Parse the response body with response.json() or response.text() as needed.
Run Deno scripts with --allow-net to enable network requests.
Remember to await both the fetch call and the response parsing.