Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse link header from github API

the github API sends the pagination data for the json results in the http link header:

Link: <https://api.github.com/repos?page=3&per_page=100>; rel="next", <https://api.github.com/repos?page=50&per_page=100>; rel="last" 

since the github API is not the only API using this method (i think) i wanted to ask if someone has a useful little snippet to parse the link header (and convert it to an array for example) so that i can use it for my js app.

i googled around but found nothing useful regarding how to parse pagination from json APIs

like image 574
toxinlabs Avatar asked Jan 04 '12 23:01

toxinlabs


2 Answers

The parse-link-header NPM module exists for this purpose; its source can be found on github under a MIT license (free for commercial use).

Installation is as simple as:

npm install parse-link-header 

Usage looks like the following:

var parse = require('parse-link-header'); var parsed = parse('<https://api.github.com/repos?page=3&per_page=100>; rel="next", <https://api.github.com/repos?page=50&per_page=100>; rel="last"') 

...after which one has parsed.next, parsed.last, etc:

{ next:    { page: '3',      per_page: '100',      rel: 'next',      url: 'https://api.github.com/repos?page=3&per_page=100' },   last:    { page: '50',      per_page: '100',      rel: 'last',      url: ' https://api.github.com/repos?page=50&per_page=100' } } 
like image 153
Cosmin Avatar answered Oct 08 '22 23:10

Cosmin


There is a PageLinks class in the GitHub Java API that shows how to parse the Link header.

like image 34
Kevin Sawicki Avatar answered Oct 08 '22 22:10

Kevin Sawicki