I’m trying to use the github api for searching code given keywords. I have 3 usecases, where I need to search
- within a repo
- within a org
- across all of github
There’s two ways to do that, /search/code
and /search?q=...&type=code
. There’s also the github search code UI.
And there’s tons of documentation around all three; and they seem to be mixed and referring to each other.
I’m really confused as to which one I should be using and looking at. Mainly I want to understand which endpoint to use, and what params I have to construct the query.
- https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28
- https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28#constructing-a-search-query
- https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28#search-code
- https://docs.github.com/en/search-github/searching-on-github
- https://docs.github.com/en/search-github/github-code-search/understanding-github-code-search-syntax
- etc.
1
/search/code is the easiest endpoint to use as it supports searching in all three scopes you mentioned: repo
, org
and GitHub
. You would need to use a single q
parameter that contains your query keyword as well as sub-parameters.
The good point about this endpoint is that you can build your query in github.com search box and then copy and paste it as a q
parameter. The query will contain spaces that you will need to replace with ‘+’. You may need to url encode your keywords if they contain special characters like / or & that are used to structure a URL.
Here I am using GitHub CLI to return shell code fragments that reference PATH environment variable in a specific repo:
export GH_TOKEN=<your Personal Access Token>
gh api '/search/code?q="$PATH"+language:Shell+repo:mfederczuk/system-setup'
--header "Accept: application/vnd.github.v3.text-match+json"
| jq -r '.items[].text_matches[] | .object_url, .fragment, "n"'
The header instructs the API to return code fragments. The output is:
https://api.github.com/repositories/606455180/contents/bin/rmtree.sh?ref=560d6f04815cd4d9747de2627a2e2e3a374a60ca
for path in "$@"; do
path="$(normalize_pathname "$path" && printf x)"
path="${path%x}"
https://api.github.com/repositories/606455180/contents/bin/rmtree.sh?ref=560d6f04815cd4d9747de2627a2e2e3a374a60ca
if [ ! -e "$path" ]; then
printf '%s: %s: no such directoryn' "$argv0" "$path" >&2