Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Changes between API V1 and API V2 (migration assistance)
#1
Exclamation 
Understanding the new API V2 Features:

Important: If you want to access the API V2 with inserting the API key in the URL =>  thats not longer supported!  You need to check the "CORS" section in this post!

New Features:

Placeholder..



CORS: (Cross-Origin Resource Sharing)

Understanding CORS Preflight Requests: Cross-Origin Resource Sharing (CORS) is a fundamental concept in web development, crucial for enabling secure and controlled access to resources across different domains. At the heart of this mechanism is the CORS preflight request, an essential process that browsers perform to ensure that a client-side web application can safely request resources from a server hosted on a different origin. Understanding this process is key for developers, especially when faced with the common ‘blocked by CORS policy’ error, which indicates a misconfiguration in CORS settings.

Preflight requests use the HTTP OPTIONS method, and they include headers that specify the HTTP method and headers that the actual request will use. When a server receives a preflight request, it responds with the appropriate CORS headers to indicate whether or not the actual request is allowed.

How CORS Preflight Requests are Triggered: CORS preflight requests are triggered automatically by the browser under certain conditions. These conditions include: HTTP methods other than GET, HEAD, or POST. POST requests with content types other than application/x-www-form-urlencoded, multipart/form-data, or text/plain. Requests that set custom headers. For example, a client application making a POST request with JSON data to a server on a different domain will trigger a preflight request. This is because the content type application/json is not one of the simple types, and thus the browser needs to confirm that the server accepts requests of this nature.

   

Wikipedia: https://en.wikipedia.org/wiki/Cross-orig...ce_sharing



Here a Example for Javascript - Jquery: (to get league data)

Code:
//Get League Data
//change 00000000 => to your API KEY!

var fbURLv2="https://www.thesportsdb.com/api/v2/json/all/leagues";
var commentdata = "";
$.ajax({
    url: fbURLv2,
    data: "message="+commentdata,
    dataType: "json",
    type: 'POST',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-API-KEY', '00000000');
        xhr.setRequestHeader('Content-Type', 'application/json');
    },
    // If success         
    success: function (resp) {
        console.log(resp);
    },
    // If error
    error: function(e) {
        console.log(e);
    }
});

The most important part is: (It is important to send the authentication before retrieving further data)

Code:
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-API-KEY', '00000000');
        xhr.setRequestHeader('Content-Type', 'application/json');
    },

You can also set this once for all calls: (Through ajax setup it is automatically added to every call)

Code:
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-API-KEY': '00000000');
    }
});



Here is a Example from PHP:  (Function for GET, POST, PUT & DELETE)

Code:
//Function for API Calls Version 2
function callAPI($method, $url, $data, $api_key)
{
    $curl = curl_init();
    switch (strtoupper($method)) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            if ($data) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            break;
        default:
            if ($data) {
                $url = sprintf("%s?%s", $url, http_build_query($data));
            }
    }
    // OPTIONS:
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        "X-API-KEY:" .$api_key,
        "Content-Type: application/json",
    ]);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    // EXECUTE:
    $result = curl_exec($curl);
    if (!$result) {
        die("Connection Failure");
    }
    curl_close($curl);
    return $result;
}

The most important part is: ($api_key = Your API Key)

Code:
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        "X-API-KEY:" .$api_key,
        "Content-Type: application/json",
    ]);

PHP Example to get all Sports: (with the function)

Code:
//Your Api Key
$api_key = "00000";
$get_data = callAPI('GET', 'https://www.thesportsdb.com/api/v2/json/all/sports', false, $api_key);
$response = json_decode($get_data, true);
try {
    $sports_data = $response;
}
catch(Exception $e) {
    $errors = $response['Message'];
    echo "<p>Error API: " . htmlspecialchars($errors) . "</p>";
    echo "<p>Error PHP: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</p>";
    throw new Exception('Failed to fetch data from the API.');
    exit;
}
// Loop through each sport and display the name and image
foreach ($sports_data['all'] as $sport) {
    $sport_name = htmlspecialchars($sport['strSport']); // Get and sanitize the sport name
    $sport_img = $sport['strSportThumb']; // Get the sport image URL from strSportThumb
    // Display the sport image and name
    echo "
        <div class='sport-item'>
            <div class='sport-image' style='background-image: url(" . htmlspecialchars($sport_img) . ");'>
                <div class='sport-name'>" . htmlspecialchars($sport_name) . "</div>
            </div>
        </div>
    ";
}

Download this example with much more Code: PHP TSDB TV-Guide (Vilhao)
Live Example: https://tsdb.club/Presentation_of_projec...isplay.php
Source - Presentation of your projects: [WebProject - API V1+V2] TSDB TV-Guide (Vilhao)
Task - Community: Whoever develops the script further, not only makes it more beautiful, but also allows you to click on events, view the players in detail and find out details about the broadcasters... will receive an API KEY from me for 1 year. However, the project must be made available for everyone to use for at least 1 year and presented on this page. (Begin: DD/MM/YY GMT+2 20.08.2024 23:15:00)



Here is a Example from Python:  (to get league data)

Code:
### Get League Data
### Change 00000000 => to your API KEY!

import requests

url = "https://www.thesportsdb.com/api/v2/json/all/leagues"
api_key = 00000000

headers = {
    "X-API-KEY": f"{api_key}",
    "Content-Type": "application/json"
}

response = requests.get(url, headers = headers)

if response.status_code == 200:
    print(response.json())
else:
    print(f"Request failed with status code: {response.status_code}")

The most important part:

Code:
headers = {
    "X-API-KEY": f"{api_key}",
    "Content-Type": "application/json"
}

Presented more simply:

Code:
headers = {
    "X-API-KEY": "00000000",
    "Content-Type": "application/json"
}



Our Rest Api Tool: (Your Api Key is save) - Full Version: API Tester



Browser extension test: (Talend API Tester Website: https://chromewebstore.google.com/detail...liamlcdmfm)

   
Please use: X-API-KEY and not  X_API_KEY


Or simpler, online web service: https://httpie.io/ (click Go to App)

   
   
Please use: X-API-KEY and not  X_API_KEY


Server:

If you want to allow requests for your project, you can activate CORS in your PHP script. (server side)
Simple call the functions cors() each time.

PHP Code:
<?php 
function cors() {
   
   
// Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
   
   
// Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
       
       
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
       
       
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
   
       
exit(0);
    }
   
   
echo "You have CORS!";
}
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)