back
Back

Could you provide example code to integrate the API?

avatar
Admin
Site Admin
02 June 2022, 10:43
C#/.NET

using System;
using System.Collections.Generic;
using System.Net;

// -------------------------------------------------------------------------
// if using .NET Framework
// https://docs.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer?view=netframework-4.8
// This requires including the reference to System.Web.Extensions in your project
using System.Web.Script.Serialization;
// -------------------------------------------------------------------------
// if using .Net Core
// https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=net-5.0
using System.Text.Json;
// -------------------------------------------------------------------------

namespace ConsoleTests
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string QUERY_URL = "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY"
            Uri queryUri = new Uri(QUERY_URL);

            using (WebClient client = new WebClient())
            {
                 // -------------------------------------------------------------------------
                 // if using .NET Framework (System.Web.Script.Serialization)

                JavaScriptSerializer js = new JavaScriptSerializer();
                dynamic json_data = js.Deserialize(client.DownloadString(queryUri), typeof(object));

                // -------------------------------------------------------------------------
                // if using .NET Core (System.Text.Json)
                // using .NET Core libraries to parse JSON is more complicated. For an informative blog post
                // https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

                dynamic json_data = JsonSerializer.Deserialize>(client.DownloadString(queryUri));

            }
        }
    }
}

---
C# - RestSharp

var client = new RestClient("https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

---
cURL

curl --location --request GET 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY'

---
Dart - http

var request = http.Request('GET', Uri.parse('https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY'));


http.StreamedResponse response = await request.send();

if (response.statusCode == 200) {
  print(await response.stream.bytesToString());
}
else {
  print(response.reasonPhrase);
}

---
Go - Native

package main

import (
  "fmt"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}


---
Java - OkHttp

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
  .url("https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY")
  .method("GET", body)
  .build();
Response response = client.newCall(request).execute();


---
Java - Unirest


Unirest.setTimeouts(0, 0);
HttpResponse response = Unirest.get("https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY")
  .asString();


---
JavaScript - Fetch


var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
  
--- 
JavaScript - jQuery

var settings = {
  "url": "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY",
  "method": "GET",
  "timeout": 0,
};

$.ajax(settings).done(function (response) {
  console.log(response);
});


---
JavaScript - XHR

// WARNING: For GET requests, body is set to null by browsers.

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY");

xhr.send();

---
C - libcurl

CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
  curl_easy_setopt(curl, CURLOPT_URL, "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);


---
NodeJs - Axios

var axios = require('axios');

var config = {
  method: 'get',
  url: 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY',
  headers: { }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});


---
NodeJs - Native

var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'GET',
  'hostname': 'cryptonews-api.com',
  'path': '/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY',
  'headers': {
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

req.end();


---
NodeJs - Request

var request = require('request');
var options = {
  'method': 'GET',
  'url': 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY',
  'headers': {
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});


---
NodeJs - Unirest

var unirest = require('unirest');
var req = unirest('GET', 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY')
  .end(function (res) { 
    if (res.error) throw new Error(res.error); 
    console.log(res.raw_body);
  });


---
Objective-C - NSURLSession

#import 

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY"]
  cachePolicy:NSURLRequestUseProtocolCachePolicy
  timeoutInterval:10.0];

[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  if (error) {
    NSLog(@"%@", error);
    dispatch_semaphore_signal(sema);
  } else {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSError *parseError = nil;
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    NSLog(@"%@",responseDictionary);
    dispatch_semaphore_signal(sema);
  }
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

---
OCaml - Cohttp

open Lwt
open Cohttp
open Cohttp_lwt_unix

let reqBody = 
  let uri = Uri.of_string "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY" in
  Client.call `GET uri >>= fun (_resp, body) ->
  body |> Cohttp_lwt.Body.to_string >|= fun body -> body

let () =
  let respBody = Lwt_main.run reqBody in
  print_endline (respBody)
  
---
PHP - cURL

 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;


---

PHP file_get_contents


PHP - Guzzle

sendAsync($request)->wait();
echo $res->getBody();


---
PHP - HTTP_Request2

setUrl('https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}


---
PHP - pecl_http

setRequestUrl('https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY');
$request->setRequestMethod('GET');
$request->setOptions(array());

$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();


----
PowerShell - RestMethod

$response = Invoke-RestMethod 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY' -Method 'GET' -Headers $headers
$response | ConvertTo-Json

---
Python - http.client

import http.client

conn = http.client.HTTPSConnection("cryptonews-api.com")
payload = ''
headers = {}
conn.request("GET", "/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

---
Python - Requests

import requests

url = "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY"

payload={}
headers = {}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


---
R - httr

library(httr)

res <- VERB("GET", url = "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY")

cat(content(res, 'text'))

---
R - RCurl

library(RCurl)
res <- getURL("https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY", .opts=list(followlocation = TRUE))
cat(res)

---
Ruby - Net::HTTP

require "uri"
require "net/http"

url = URI("https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Get.new(url)

response = https.request(request)
puts response.read_body


---
Shell - Httpie

http --follow --timeout 3600 GET 'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY'

---
Shell - wget

wget --no-check-certificate --quiet \
  --method GET \
  --timeout=0 \
  --header '' \
   'https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY'
   
---
Swift - URLSession

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

var semaphore = DispatchSemaphore (value: 0)

var request = URLRequest(url: URL(string: "https://cryptonews-api.com/api/v1?tickers=BTC&items=50&page=1&token=GET_API_KEY")!,timeoutInterval: Double.infinity)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    print(String(describing: error))
    semaphore.signal()
    return
  }
  print(String(data: data, encoding: .utf8)!)
  semaphore.signal()
}

task.resume()
semaphore.wait()

---

To see the endpoints we provide check our documentation page.

Ben