Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

Github API: determine if user or org

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?

Upvotes: 4

Views: 1830

Answers (2)

S Raghav
S Raghav

Reputation: 1526

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

Upvotes: 9

Mario
Mario

Reputation: 36487

So even if there's an API call to differentiate, you'll still need that call to determine whether it's a user or not.

Considering the fact that most repositories should belong to users, why don't you reverse the checks? Try to retrieve the user repository, if that fails get the organization repository.

In addition, I'd cache as much information as necessary. Don't retrieve everything in real time while users use your tool. Many things won't change that often, if they're even able to be changed.

Upvotes: 1

Related Questions