Deno HTTP

Deno can be used to fetch data from the webserver using HTTP requests.

Deno provides the web standard fetch API to make HTTP calls.

This chapter teaches how to make HTTP calls in your Deno program.

Deno Make HTTP Request and Display to Terminal

The following example makes a call to the URL provided as an argument in the terminal, then prints the response to the terminal.

Tip

  • In the project folder hello, create a new file deno_http_request.js

Deno Live Example: deno_http_request.js

const url = Deno.args[0];
const res = await fetch(url);

const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);
  Do It Yourself

Example Explained

  • The first part of the code gets the first argument passed to the terminal, and store it in the link variable.
  • The second part of the code makes a request to the link variable, which returns a promise stored in a res variable.
  • After awaiting the response from the res variable, the third part of the code parses it as an ArrayBuffer and convert it into a Uint8Array to store in the body constant.
  • The last parts of the code write it to the stdout which displays in the terminal.

Run the code

Run the code by providing a URL as the first argument:

In our case, we going to be using IP API which provides some important details about out IP. Feel free to use any URL: http://ip-api.com/csv

deno run --allow-net deno_http_request.js http://ip-api.com/csv
Note: Don't forget the --allow-net flag which gives Deno permission to access the network, Deno will throw an error without this permission.

The 'Next Chapter' teaches how to handle files in Deno.

What You Should Know At The End of This Chapter

  • You should be able to understand and use the fetch() method.
  • You should be able to create and run the HTTP Request program