Help passing API key though query string

I’m currently learning to work with api’s, and I wanted to use bing search news api through azure.

In the past, whenever I’ve used the fetch API it just looks like:

const NEWS_URL = 'https://someurlhere.com'

  fetch(NEWS_URL)
  .then((response) => {
    return response.json();
  })
  .then((newsJSON) => {

    const news = newsJSON

    //code here
}

But now that I have the API key, azure says " key needs to be either passed through a query string parameter or specified in the request header"

I thought I could just set the api key to a variable then put it in the url using ${key}, but that isn’t working.

Can someone point me in the right direction.

Thanks!

I don’t have time to look it up atm, but every api is different. Are there no docs and/or examples?

There are docs: https://docs.microsoft.com/en-us/rest/api/cognitiveservices-bingsearch/bing-news-api-v7-reference

but the example it gives is just : https://api.cognitive.microsoft.com/bing/v7.0/news

I’ve tried every way I can think of to input the key to the url.

fetch accepts as the second parameter, some request options in an object. I might try:

const myKey = '123456';
const requestHeaders = {
    headers: {
      'Ocp-Apim-Subscription-Key': myKey,
    },
};

fetch(NEWS_URL, requestOptions)
  .then((response) => {
  // ...

Why that property name for the key? I’m kind of guessing, because the site provides this curl example:

GET https://api.cognitive.microsoft.com/bing/v7.0/news/search?q=sailing+dinghies&mkt=en-us HTTP/1.1
Ocp-Apim-Subscription-Key: 123456789ABCDE
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822)
X-Search-ClientIP: 999.999.999.999
X-Search-Location: lat:47.60357;long:-122.3295;re:100
X-MSEdge-ClientID: <blobFromPriorResponseGoesHere>
Host: api.cognitive.microsoft.com

So, try that out. And if it doesn’t work, try to get the error message.

Hmm. It’s still getting the error: net::ERR_NAME_NOT_RESOLVED

and failed to fetch.

Why what property name for the key?

That err (akaik) means that the url can’t be found. What is the code you are trying to run. Please don’t include your API key, pm it to me separately.

const api = '00000000000';
const requestHeaders = {
    headers: {
      'Ocp-Apim-Subscription-Key': api,
    },
};

const NEWS_URL = 'https://api.pistons-news.cognitiveservices.azure.com/bing/v7.0/news'

  fetch(NEWS_URL, requestHeaders )
  .then((response) => {
    return response.json();
  })
  .then((newsJSON) => {
    //Set the JSON data for games to a variable
    const stonsNews = newsJSON



  });

Hi Randell, it’s the custom endpoint that azure gave me to make API calls. I had to create a new resource in azure to get the api key, and set a custom url.

I agree with Randy. If I swap out the URL for the one in the curl example above…

const NEWS_URL = 'https://api.cognitive.microsoft.com/bing/v7.0/news/search?q=sailing+dinghies&mkt=en-us'

I get a valid response:

{
  _type: 'News',
  readLink: 'https://api.cognitive.microsoft.com/api/v7/news/search?q=sailing+dinghies',
  queryContext: {
    originalQuery: 'sailing dinghies',
    adultIntent: false
  },
  totalEstimatedMatches: 43900,
  sort: [
    {
      name: 'Best match',
      id: 'relevance',
      isSelected: true,
      url: 'https://api.cognitive.microsoft.com/api/v7/news/search?q=sailing+dinghies'
    },
    {
      name: 'Most recent',
      id: 'date',
      isSelected: false,
      url: 'https://api.cognitive.microsoft.com/api/v7/news/search?q=sailing+dinghies&sortby=date'
    }
  ],
  value: [
    {
      name: 'Mum who sailed her kids across the Channel in a dinghy after leaving wife for sperm donor walks free from court',
      url: 'https://www.thesun.co.uk/news/10783742/mum-dinghy-cross-channel-kids-let-off/',
      image: {
        thumbnail: {
          contentUrl: 'https://www.bing.com/th?id=ON.01E034E3A43C50DC7761B0F3A27BB000&pid=News',
          width: 700,
          height: 466
        }
      },
      description: 'A BRITISH mum convicted of putting her two kids at risk of harm after sailing them in a dinghy across the Channel has walked free from court. Lauren Etchells, 34, breached a court order and fled Canada after splitting from a partner. Lauren Etchells at court after being convicted of putting her two kids at risk of harm by crossing the Channel ...',
      provider: [
        {
          _type: 'Organization',
          name: 'The Sun',
          image: {
            thumbnail: {
              contentUrl: 'https://www.bing.com/th?id=AR_f0444eed92ae4ac33c1cd3baa785e988&pid=news'
            }
          }
        }
      ],
      datePublished: '2020-01-21T01:29:00.0000000Z',
      category: 'World',
      ampUrl: 'https://www.thesun.co.uk/news/10783742/mum-dinghy-cross-channel-kids-let-off/amp/'
    },
// ...

And just to be nitpicky (about my own advice), requestOptions is a better variable name than requestHeaders.

Oh sorry, I noticed it said requestOptions for the variable, but then in the .fetch it said requestHeaders.

Thank you guys though! I’m not sure what I could’ve been doing wrong.

Do you have any idea what that url they gave me is for then? when I’m logged into azure it says to use that as the endpoint.

Right, the headers are one of the request options - there are others.

I’m not sure about the end point. Maybe it is a custom thing and needs to be setup better. Idk.