Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deno - How to fetch data from distant API or URL?

Tags:

deno

I'm wondering how I can get data from other servers and API with deno ? Everything in the documentation teach me about making http servers and read files from local source. But I can't find anything useful about reading something on the network.

How can read JSON data from the Stripe API ? Or if I want to read a HTML file with text inside ?

Thank you for your time!

like image 461
Tryall Avatar asked Dec 13 '22 08:12

Tryall


1 Answers

I am just giving you an example of the GET request for fetching repositories of Github.

You can change the URL and Request Configuration as per your need.

In the code given below, I am calling another API of Github. By using the fetch() method you can do that.

fetch() method first takes the URL as the first parameter and the next parameter is RequestInit which takes the request method type, headers, body, etc and at the end returning JSON response of that API call.

const githubResponse = async (): Promise<any> => {
    const response = await fetch("https://api.github.com/search/repositories?q=android", {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
        },
    });
    return response.json(); // For JSON Response
    //   return response.text(); // For HTML or Text Response
}

console.log(await githubResponse());

I have written the above code in a ts file named Testing.ts . So, you can run the above code by the command given below:

deno run --allow-net Testing.ts

Next, I am giving you a sample POST request code:

const githubResponse = async (): Promise<any> => {
    const body: URLSearchParams = new URLSearchParams({
        q: "AvijitKarmakar",
    });

    const response = await fetch("https://api.github.com/search/repositories", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: body
    });
    return response.json();
    //   return response.text(); // For HTML or Text Response
}

console.log(await githubResponse());

You can see that I have created a body object and passed it in the RequestInit through the body parameter and also changed the request method type to POST.

like image 173
Avijit Karmakar Avatar answered Feb 23 '23 11:02

Avijit Karmakar