How Can I Get All Data from a Json Api When Pagination Is Enabled?

I need to get all data from this api: , but I'm getting the first page(page 1) data with this code:

urlApi = '

let repo = await axios.get(urlApi);
repo.data.hits.map((data) => {
    console.log(data);
 });

This JSON contains 'nbPages': 50, But I need to map all 50 JSON pages.

Do you have any ideas for mapping?

0

2 Answers

You could use a while loop and just append the hits to an array until you've completed all requests:

let repo = null, page = 0, results = [];
do {
    repo = await axios.get(`${urlApi}&page=${page++}`);
    results = results.concat(repo.data.hits);
} while(repo.data.page < repo.data.nbPages)

console.log(results);
1

Due to the fact that the standard value for "hitsPerPage" is 20, you can set this value to get all of the hits at once by using this URL instead (20 hits * 50 pages = 1000):

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest