loading...

Query the total number of items from an API?

github logo ・1 min read

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?

twitter logo DISCUSS (10)
markdown guide
 

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

 

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 :/

 
 

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?

 

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);
}

 

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

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

 

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.

 

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

Classic DEV Post from Aug 4 '19

You're not worth hiring unless...

Horváth Donát profile image
I a freshly graduated bootcamp coder, so my knowledge is not so deep yet. To compensate this I am eager to learn!