Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Github API: determine if user or org

Tags:

github-api

Given the URL https://github.com/foo/bar, I want to be able to get all the repos for foo. If foo is a user, I need to call api.repos.getForUser({username: 'foo'}) and if an org, I'll need to call api.repos.getForOrg({org: 'foo'}).

My problem is: how can I tell if "foo" is an org or a user?

Right now, I "solve" it in the costly way of trying to get an org called "foo", if I got it, I try to get its repos; if I end up getting an exception (I use promises) and if the code of the exception is "404", I assume "foo" is a user, and try to get user repos.

This is obviously inefficient, and has the side effect of adding calls that may trigger rate limit.

Is there an easier way to know whether "foo" is a user or an org?

like image 1000
Traveling Tech Guy Avatar asked Oct 27 '25 14:10

Traveling Tech Guy


1 Answers

As we all know, handling exceptions is costly. So instead of trying to get an org and handling the 404, you could instead look at the type property of the response to https://api.github.com/users/<username> in order to determine if the "user" is a user or organization and then proceed accordingly.

For example a call to my GitHub user API https://api.github.com/users/raghav710 returns

{
  "login": "raghav710",
  ...
  "type": "User",
  ...
}

And a call to an organization like https://api.github.com/users/Microsoft returns

 {
   "login": "Microsoft",
   ...
   "type": "Organization",
   ...
}

Update: Doing it in a single call

I understand that you are already trying to access a URL https://github.com/<user or organization>/<repo name> and therein trying to get all the repos of that user or organization.

A suggestion is, instead of trying to do a GET on the above link, you could do a GET on https://api.github.com/repos/<user or organization>/<repo name>

For example doing a GET on https://api.github.com/repos/Microsoft/vscode

Gives

{
    "id": 41881900,
    "name": "vscode",
    "full_name": "Microsoft/vscode",
    "owner": {
        "login": "Microsoft",
        "id": 6154722,
        ...
        "type": "Organization",
    },
    "private": false,
    "html_url": "https://github.com/Microsoft/vscode",
    ...
}

As you can see the familiar type field is available under the owner key. You can use this to decide your next call

like image 152
raghav710 Avatar answered Oct 30 '25 13:10

raghav710