[Support Guide] Linking a repository via API

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).

   "cmd":"jekyll build",

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’ll need to change the value of provider based on what you use - “github”, “gitlab”, “bitbucket”, and “manual” are the options. manual is intended for anything other than github.com, gitlab.com, or bitbucket.org as of June 2020.

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