WordPress keyed API call help

[ad_1]

Hi all,

I’m new to this API business and WordPress, so go easy on me.

I’m tryin got set up an API call on a WordPress site using PHP, right now I’m just trying to get a simple call to work using the wp\_remote\_get() command:

https://preview.redd.it/ndki0mmac7yc1.png?width=460&format=png&auto=webp&s=95af6975a9866a4946438b67371cafa36a67cc1c

I’m simply hitting the API sport url and passing my api key as an argument (per the WordPress wp\_remote\_get documentation). Meanwhile I get a response from the api saying I failed to provide an API key.

I’ve been able to successfully pull JSON data from the api when using the fully constructed URL’s, (or whatever they’re called), with the ?apikey= bit added in directly e.g. [https://api.the-odds-api.com/v4/sports/?apiKey=YOUR\_API\_KEY](https://api.the-odds-api.com/v4/sports/?apiKey=YOUR_API_KEY)

What am I doing wrong here?

Any help is appreciated, if there is another sub I should post this in please let me know, thanks!

[ad_2]
2 Comments
  1. In GET requests api keys are either added as get parameter to the url or passed through headers, since the GET Method doesn’t have a payload like body does.

    IN short your second approach is the correct way to do It, although I would recommend you might use a constant in your wp-config and reference the variable here.

  2. You’re not passing the API key correctly and you’re not using the $args parameter correctly. $args parameter in the wp_remote_get() takes an array as a value.

    You have a few options here:

    1. Pass the API key directly to the url so $url would be “https://api.the-odds-api.com/v4/sports/?apiKey=YOUR_API_KEY”. After this you can remove your $url and $args variables.
    2. Use add_query_arg() -function. This will allow you to add more query variables later with filters for example. add_query_args() -function will append the apikey to your url the same way as ins option 1. In this case you would use it like this

    $apiKey = “YOUR_API_KEY”;
    $url = add_query_arg( ‘apiKey’, $apiKey, ‘https://api.the-odds-api.com/v4/sports’;
    $response = wp_remote_get( $url );
    3. Pass your API key to the request body. Here you need to use the $args parameter. You will have to test if this works with your API. It would go something like this:

    $args = array(
    ‘body’ => array(
    ‘apiKey’ => ‘YOUR_API_KEY’
    )
    );
    $response = wp_remote_get( $url, $args );

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer