How to Make HTTP Request in Deno: Simple Guide
In Deno, you make HTTP requests using the built-in
fetch function, which works like in browsers. You call fetch(url) to send a request and then use await to get the response and read its data.Syntax
The basic syntax to make an HTTP request in Deno uses the fetch function:
fetch(url, options): Sends a request to the given URL.url: The address you want to request.options: Optional object to specify method, headers, body, etc.await: Used to wait for the response asynchronously.response.json()orresponse.text(): Methods to read the response data.
typescript
const response = await fetch('https://example.com/api', { method: 'POST', // or 'GET', 'PUT', etc. headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) // only for methods like POST }); const data = await response.json();
Example
This example shows how to make a GET request to fetch JSON data from a public API and print it to the console.
typescript
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); if (!response.ok) { console.error('HTTP error:', response.status); } else { const todo = await response.json(); console.log('Todo item:', todo); }
Output
{"userId":1,"id":1,"title":"delectus aut autem","completed":false}
Common Pitfalls
Common mistakes when making HTTP requests in Deno include:
- Not using
awaitwithfetch, which causes unresolved promises. - Ignoring the
response.okproperty to check if the request succeeded. - Forgetting to set the correct
Content-Typeheader when sending JSON data. - Trying to read the response body multiple times, which is not allowed.
typescript
/* Wrong way: Missing await and no error check */ const response = fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); // Error: response is a Promise, not Response /* Right way: Use await and check response.ok */ const responseCorrect = await fetch('https://jsonplaceholder.typicode.com/todos/1'); if (responseCorrect.ok) { const dataCorrect = await responseCorrect.json(); console.log(dataCorrect); } else { console.error('Request failed with status', responseCorrect.status); }
Quick Reference
Here is a quick summary of key points for HTTP requests in Deno:
- Use
fetch(url, options)to send requests. - Always
awaitthe fetch call to get the response. - Check
response.okto confirm success. - Use
response.json()orresponse.text()to read data. - Set headers like
Content-Typewhen sending JSON.
Key Takeaways
Use the built-in fetch function with await to make HTTP requests in Deno.
Always check response.ok to handle errors properly.
Set appropriate headers when sending data, especially Content-Type for JSON.
Read the response body only once using methods like response.json() or response.text().
Remember fetch works like in browsers, so no extra libraries are needed.