[Common Issue] Linking a repository via API

answered
#1

While it is easier to link a repository in Netlify’s UI than programatically, there are cases in which you don’t want to do that. Fortunately, it is possible to use Netlify’s REST API for these situations. You’ll probably be interested in the general topics around “how do I use Netlify’s REST API?” and our public documentation on the topic.

You can link a repository while you create a site. This is an example payload from such a successful site creation (sent via HTTP POST to https://api.netlify.com/api/v1/sites).

{"repo":
  {"provider":"github",
   "id":74777123,
   "repo":"account_name/repository_name",
   "private":false,
   "branch":"master",
   "cmd":"jekyll build",
   "dir":"_site/",
   "deploy_key_id":"5a908857a6188f466bed"
   }
}

Note that there are two ID’s there - a GitHub repo ID (which you can get from their API) - and similar ID’s are needed for GitLab and BitBucket as well. The second ID is a deploy key ID . You’ll need to create the Deploy Key via our API before you’ll be able to create a usable repo object, so this is the call you have to make FIRST, before creating the site.

The call to achieve this is an HTTP POST to https://api.netlify.com/api/v1/deploy_keys . This call responds with JSON containing public_key and id parameters (you’ll need to put the public_key in place at your git provider), and keep the id value, for using with the repo definition I already quoted.

You can also use our CLI to link a repo, see this forum thread for more details.

1 Like
[Common Issue] Understanding and using Netlify's API