Code examples
In this page you will find examples for request our endpoints in different programming languages:
cURL
curl --location --request GET 'https://{sport}.sportdevs.com/{endpoint}' \
--header 'Authorization: Bearer {API-KEY}'
C# - RestSharp
var client = new RestClient("https://{sport}.sportdevs.com/{endpoint}");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer {API-KEY}");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Dart - http
var headers = {
'Authorization': 'Bearer {API-KEY}'
};
var request = http.Request('GET', Uri.parse('https://{sport}.sportdevs.com/{endpoint}'));
request.headers.addAll(headers);
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://{sport}.sportdevs.com/{endpoint}"
method := "GET"
client := &http.Client {
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer {API-KEY}")
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))
}
HTTP
GET /{endpoint} HTTP/1.1
Host: {sport}.sportdevs.com
Authorization: Bearer {API-KEY}
Java
Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.get("https://{sport}.sportdevs.com/{endpoint}")
.header("Authorization", "Bearer {API-KEY}")
.asString();
JavaScript - Fetch
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer {API-KEY}");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://{sport}.sportdevs.com/{endpoint}", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error))
JavaScript - jQuery
var settings = {
"url": "https://{sport}.sportdevs.com/{endpoint}",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer {API-KEY}"
},
};
$.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://{sport}.sportdevs.com/{endpoint}");
xhr.setRequestHeader("Authorization", "Bearer {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://{sport}.sportdevs.com/{endpoint}");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Authorization: Bearer {API-KEY}");
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://{sport}.sportdevs.com/{endpoint}',
headers: {
'Authorization': 'Bearer {API-KEY}'
}
};
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': '{sport}.sportdevs.com',
'path': '/{endpoint}',
'headers': {
'Authorization': 'Bearer {API-KEY}'
},
'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://{sport}.sportdevs.com/{endpoint}',
'headers': {
'Authorization': 'Bearer {API-KEY}'
}
};
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://{sport}.sportdevs.com/{endpoint}')
.headers({
'Authorization': 'Bearer {API-KEY}'
})
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
Objective-C - NSURLSession
#import <Foundation/Foundation.h>
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{sport}.sportdevs.com/{endpoint}"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSDictionary *headers = @{
@"Authorization": @"Bearer {API-KEY}"
};
[request setAllHTTPHeaderFields:headers];
[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://{sport}.sportdevs.com/{endpoint}" in
let headers = Header.init ()
|> fun h -> Header.add h "Authorization" "Bearer {API-KEY}"
in
Client.call ~headers `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
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://{sport}.sportdevs.com/{endpoint}',
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',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer {API-KEY}'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
PHP - Guzzle
<?php
$client = new Client();
$headers = [
'Authorization' => 'Bearer {API-KEY}'
];
$request = new Request('GET', 'https://{sport}.sportdevs.com/{endpoint}', $headers);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();
PHP - HTTP_Request2
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://{sport}.sportdevs.com/{endpoint}');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
'follow_redirects' => TRUE
));
$request->setHeader(array(
'Authorization' => 'Bearer {API-KEY}'
));
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
<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://{sport}.sportdevs.com/{endpoint}');
$request->setRequestMethod('GET');
$request->setOptions(array());
$request->setHeaders(array(
'Authorization' => 'Bearer {API-KEY}'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
PowerShell - RestMethod
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer {API-KEY}")
$response = Invoke-RestMethod 'https://{sport}.sportdevs.com/{endpoint}' -Method 'GET' -Headers $headers
$response | ConvertTo-Json
Python - http.client
import http.client
conn = http.client.HTTPSConnection("{sport}.sportdevs.com")
payload = ''
headers = {
'Authorization': 'Bearer {API-KEY}'
}
conn.request("GET", "/{endpoint}", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Python - Requests
import requests
url = "https://{sport}.sportdevs.com/{endpoint}"
payload={}
headers = {
'Authorization': 'Bearer {API-KEY}'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
R - httr
library(httr)
headers = c(
'Authorization' = 'Bearer {API-KEY}'
)
res <- VERB("GET", url = "https://{sport}.sportdevs.com/{endpoint}", add_headers(headers))
cat(content(res, 'text'))
R - RCurl
library(RCurl)
headers = c(
"Authorization" = "Bearer {API-KEY}"
)
res <- getURL("https://{sport}.sportdevs.com/{endpoint}", .opts=list(httpheader = headers, followlocation = TRUE))
cat(res)
Ruby - Net::HTTP
require "uri"
require "net/http"
url = URI("https://{sport}.sportdevs.com/{endpoint}")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer {API-KEY}"
response = https.request(request)
puts response.read_body
Shell - Httpie
http --follow --timeout 3600 GET 'https://{sport}.sportdevs.com/{endpoint}' \
Authorization:'Bearer {API-KEY}'
Shell - wget
wget --no-check-certificate --quiet \
--method GET \
--timeout=0 \
--header 'Authorization: Bearer {API-KEY}' \
'https://{sport}.sportdevs.com/{endpoint}'
Swift - URLSession
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)
var request = URLRequest(url: URL(string: "https://{sport}.sportdevs.com/{endpoint}")!,timeoutInterval: Double.infinity)
request.addValue("Bearer {API-KEY}", forHTTPHeaderField: "Authorization")
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()