skip to Main Content

I’m having this issue with certain API’s, where invalid links are still "ok". Here for the ticker symbol I typed a bunch of random letters in place of an actual ticker: …ticker=AAsdfsPL… as opposed to …ticker=AAPL… The API link itself still doesn’t produce an error even though it doesn’t really fetch any data. Any way to fix this or do I need to use a different API?

const resStock = await fetch(
      `https://api.polygon.io/v3/reference/tickers?ticker=AAsdfsPL&active=true&apiKey=key`
    );
    console.log(resStock.ok); //still returns true even though link doesn't do anything.

2

Answers


  1. You can distiguish the result whether it contains data or not

    const resStock = await fetch(
       `https://api.polygon.io/v3/reference/tickers?ticker=AAsdfsPL&active=true&apiKey=6P2qV_oNdXnkkmnd5Vb5VtQWi09OIzfU`
    )
    
    if(resStock.results){
      //do the next steps
    }
    else {
       // you are not getting data, so throw error if you want to 
    }
    
    Login or Signup to reply.
  2. In this particular case, you can check for the count property in the returned JSON to determine whether the result is valid or not:

    (async function () {
      const resStock = await fetch(
        `https://api.polygon.io/v3/reference/tickers?ticker=AAPsL&active=true&apiKey=6P2qV_oNdXnkkmnd5Vb5VtQWi09OIzfU`
      );
      let json;
      try {
        json = await resStock.json();
      } catch (e) {
        // Ignored
      }
      const isOk = json && !!json.count;
      console.log(isOk);
    })();

    Documentation: https://polygon.io/docs/stocks/get_v3_reference_tickers

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search