List users containing a specified string using the GitHub API

This article aims to guide developers on how to use the GitHub API to retrieve a list of users whose usernames contain a specific string. Since the GitHub API limits the number of users returned each time by default, this article will introduce two pagination methods: using the pagination function provided by Octokit and manual loop query, and explain how to implement it in detail through code examples. By studying this article, you will be able to efficiently get the complete user list from the GitHub API and filter it as needed.
The GitHub API provides a powerful way to retrieve user information, but by default it limits the number of users returned per request. In order to get a complete list of users, especially when we need to search for users whose usernames contain a specific string, we need to utilize the paging mechanism. This article will introduce two methods to implement paging to help you obtain the required user information from the GitHub API efficiently.
Using Octokit’s Pagination feature
Octokit is an official JavaScript library for interacting with the GitHub API. It provides a convenient pagination function to simplify pagination operations.
The following is sample code using the Octokit pagination feature:
import { Octokit } from "octokit";
const octokit = new Octokit({
auth: 'YOUR_GITHUB_TOKEN' // Replace with your GitHub Token
});
async function listUsers(username) {
const data = await octokit.paginate("GET /search/users", {
q: username, // Use the search/users API and specify the search keyword per_page: 100, // Return 100 users per page headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
});
console.log(data);
return data;
}
// Example: Search for users whose username contains "octocat" listUsers("octocat");
Code explanation:
- import { Octokit } from "octokit"; : Import the Octokit library.
- const octokit = new Octokit({ auth: 'YOUR_GITHUB_TOKEN' }); : Create an Octokit instance and use your GitHub Token for authentication. Please be sure to replace YOUR_GITHUB_TOKEN with your real Token.
- octokit.paginate("GET /search/users", { ... }) : Use the octokit.paginate method to perform pagination queries.
- "GET /search/users": Specify the API interface to be called. The search/users interface is used here, which allows searching for users by keywords.
- q: username: The q parameter specifies the search keyword, and the passed in username parameter is used here.
- per_page: 100: Specifies to return 100 users per page, which is the maximum allowed by the API.
- headers: Set request headers and specify the GitHub API version.
- console.log(data) : Print the returned user data. data is an array containing all matching users.
Things to note:
- Please make sure you have installed the Octokit library: npm install octokit
- To avoid API rate limits, it is recommended to use GitHub Token for authentication.
- The search/users API sorts by match, not by user ID.
Manual loop query
If you don't want to use Octokit's pagination function, you can also implement paging query manually.
The following is sample code for a manual loop query:
async function listUsersManually(username) {
let users = [];
let page = 1;
const perPage = 100;
while (true) {
const response = await fetch(`https://api.github.com/search/users?q=${username}&per_page=${perPage}&page=${page}`, {
headers: {
"X-GitHub-Api-Version": "2022-11-28",
"Authorization": `token YOUR_GITHUB_TOKEN` // Replace with your GitHub Token
}
});
const data = await response.json();
if (!data.items || data.items.length === 0) {
break; // No more users, exit the loop}
users = users.concat(data.items);
if (data.items.length <p> <strong>Code explanation:</strong></p><ol>
<li> <strong>let users = [];</strong> : Initialize an empty array to store all matching users.</li>
<li> <strong>let page = 1;</strong> : initialize the page number to 1.</li>
<li> <strong>const perPage = 100;</strong> : Set the number of users returned per page to 100.</li>
<li> <strong>while (true) { ... }</strong> : Enter an infinite loop until there are no more users or an error is encountered.</li>
<li> <strong>fetch(...)</strong> : Use the fetch API to send HTTP requests.<ul>
<li> https://api.github.com/search/users?q=${username}&per_page=${perPage}&page=${page}: API URL, including search keywords, number of pages per page, and page number.</li>
<li> headers: Set request headers, specify GitHub API version and authentication token. <strong>Please be sure to replace YOUR_GITHUB_TOKEN with your real Token.</strong>
</li>
</ul>
</li>
<li> <strong>data = await response.json()</strong> : Parse JSON response.</li>
<li> <strong>if (!data.items || data.items.length === 0) { break; }</strong> : Check if there are more users. If data.items is empty or has a length of 0, it means there are no more users and the loop exits.</li>
<li> <strong>users = users.concat(data.items);</strong> : Add the users of the current page to the users array.</li>
<li> <strong>page ;</strong> : Add page number and prepare to query the next page.</li>
<li> <strong>if (data.items.length : If the number of users returned is less than perPage, it means it is the last page and exit the loop.</strong>
</li>
</ol><p> <strong>Things to note:</strong></p>
- Likewise, to avoid API rate limits, it is recommended to use GitHub Token for authentication.
- Need to handle possible errors in API requests.
- Manual looping queries require more code, but provide more flexible control over the paging process.
Summarize
This article describes two methods of using the GitHub API to list users containing a specified string: using Octokit's pagination function and manual loop query. Octokit's pagination function is more concise and convenient, while manual loop query is more flexible. You can choose the appropriate method based on your needs. When using the GitHub API, be sure to be aware of API rate limits and use GitHub Tokens for authentication. In addition, the search/users API is a powerful tool that can search for users based on various criteria, please check the GitHub API documentation for more information.
The above is the detailed content of List users containing a specified string using the GitHub API. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20515
7
13628
4
How to display last visited city and country of user on website
Mar 13, 2026 am 03:51 AM
The geographical location is obtained through the front-end and combined with the back-end storage to realize the dynamic prompt function of "the last visit was from XX city, XX country". It requires the help of IP location service, server-side persistence and front-end display logic.
The correct way to use express-validator for strong password verification
Mar 09, 2026 am 03:33 AM
This article describes how to correctly configure the isStrongPassword option when using the express-validator library for strong password validation. Highlights a known issue with schema validation mode and provides detailed steps and code examples for using chained validation as an alternative to ensure passwords meet custom strength requirements.
Tailwind CSS dynamic class name invalidation problem: principle and solution
Mar 07, 2026 am 12:30 AM
This article delves into the reason why Tailwind CSS cannot recognize dynamically generated class names (such as bg-[${variable}]) in React applications, mainly due to its JIT compiler's reliance on complete class names. The tutorial provides two effective solutions: one is to predefine the complete Tailwind class name in a variable, and the other is to use React's inline styles for specific CSS properties to help developers overcome dynamic style challenges and maintain code maintainability.
How to automate web console code execution without opening browser developer tools
Mar 05, 2026 am 06:00 AM
This article introduces the use of browser extensions (such as Tampermonkey) to automatically run JavaScript code (such as debug.start()) when the page is loaded, without manually opening DevTools; it also explains why pure Python cannot directly operate the console of an opened web page, and possible automation alternatives.
How to combine multiple regular expressions into a replacement pattern that performs efficiently
Mar 13, 2026 am 12:03 AM
This article introduces how to safely combine multiple independent regular expressions (such as URL cleaning, specific pattern word filtering, special character deletion) into a single regular expression in JavaScript through logical or (|), and implement multiple rule cleaning in one replace() to avoid repeated string traversal.
How to uniformly sample a specified number of elements (such as 5) from an array
Mar 13, 2026 am 02:42 AM
This article introduces an accurate and efficient algorithm for extracting a fixed number (such as 5) of elements that are as evenly distributed as possible from an array of any length, ensuring that the first and last elements must be selected, the middle elements are distributed proportionally, and the original order is maintained.
How to use Destructuring assignment for objects in JavaScript? (ES6 features)
Mar 05, 2026 am 02:39 AM
When deconstructing an object, if the property name is inconsistent with the variable name, you need to rename it with a colon, such as {firstName:first}; destructuring null/undefined will report a TypeError, so you should always use {}; the default value of the function parameter only takes effect for undefined, and null will still trigger destructuring failure.
Complete tutorial on naturally sorting JavaScript arrays by numbers at the end of file names
Mar 13, 2026 am 06:12 AM
This article explains in detail how to correctly numerically sort an array of file names containing increasing numeric suffixes, and solve the problem of 13810 < 13912 being misjudged as a larger problem caused by the default string sorting of Array.prototype.sort().





