DEV Community

Horváth Donát
Horváth Donát

Posted on

Query the total number of items from an API?

Hey!

I try to do a simple frontend app with Angular, which uses this Open Brewery DB API to fetch data. I would like to fetch only 10 items per page and make pagination for the rest.

My problem is that I don't know how many items are in the database so I could not calculate the maximum number of pages.

Edit: I forgot to mention that there is no endpoint given with which I could query more than 50 items at once.

Is there a way to query the total number of items from an API?

Discussion (10)

Collapse
qainsights profile image
NaveenKumar Namachivayam ⚡

How about $.length? This will give you the number of items in JSON.

Collapse
hordon profile image
Horváth Donát Author

Thank you for your reply! I forgot to mention that the server only responds with 50 items at max. So I could not query the whole dataset with one request hence I could not use $.length either I guess :/

Collapse
ankit199 profile image
Ankit kumar shukla

your item array.length

Collapse
hordon profile image
Horváth Donát Author

Yeah, but I could query only 50 with one request, so array.length would be always 50, not the number of items in the whole database, right?

Collapse
ankit199 profile image
Ankit kumar shukla

You can do something like this to get count from your top 50 array object list item

var arr =[{'id':1,name:'A',address:['A','B','C']},{'id':2,name:'B',address:['A','B','C','D']},{'id':3,name:'C',address:['A','B','C','D','E']}]

function countValue(){
//var arrData= arr.map(x=>x.address.length)
var arrData= arr.map(obj=> ({ ...obj, count: obj.address.length }))
console.table(arrData);
}

Collapse
ankit199 profile image
Ankit kumar shukla

to get number of count from DB please add a new variable to your API response field and assign total number count to it and use it in your application

Thread Thread
hordon profile image
Horváth Donát Author

Unfortunately, this is not my API, it is a publicly available open API, so I could not add variable to it :(

Thread Thread
ankit199 profile image
Ankit kumar shukla

so you cant do anything :)

Collapse
avision profile image
Arnold Velzel • Edited

Try to sort by 'id' like-

api.openbrewerydb.org/breweries?so...

That gives you at least some idea about how many records there are by check the ID of the first record.

Collapse
hordon profile image
Horváth Donát Author

Great idea, thank you! Let's hope that ids are continuous :D