Home > Enterprise >  Can URL API endpoint self-correct?
Can URL API endpoint self-correct?

Time:11-02

I am using fetch API inside a React application to retrieve and display some quiz questions. This is my url endpoint: https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple

I have noticed that:

-when I misspell part of the URL before "?" then the response doesn't get back. example:https://opentdb.com/api.ph?amount=${amount}&difficulty=${difficulty}& (missing "p" of php)

-when I misspell part of the url after "?" then, sometimes I get an empty array back, sometimes I get the data back. How can I get data back with a wrong URL? example: https://opentdb.com/api.php?amoun=${amount}&difficulty=${difficulty}&type=multiple (missing "t" in amount)

I haven't deployed the application yet, I am using vsc and run npm start to develop the application. Is it possible that the URL auto-corrects? or maybe it gets cached?

my code:

    export const fetchQuizQuestions = async (
  amount: number,
  difficulty: Difficulty
) => {
  const endPoint = `https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`;

  try {
    const response = await fetch(endPoint);
    console.log(response);

    const data = await response.json();
    console.log(data);
    if (data.results.length === 0) {
      throw new Error("The part after ? contains some mistake");
    }
    //below I create the new property "all_answers" and make sure the answers order is never the same
    return data.results.map((question: Question) => ({
      ...question,
      all_answers: shuffleArray([
        ...question.incorrect_answers,
        question.correct_answer,
      ]),
    }));
  } catch (error: any) {
    console.log(error.name);
    console.log(error.message);
  }
};

CodePudding user response:

Before the ? It's the url. So if you make a mistake there, basically it's like sending a letter to a different adress, so you will not get any answers.

After the ? it's the query string. So you're asking for a result, with some parameters (your query) So if you're saying like "ok, send me back answers with amount = XXX" but you misspell amount, it's just like "ok send me back answers" because you're not asking for amount anymore (but amoun which is nothing for the endpoint)

  • Related