[SOLVED] Add a new key via api

Hi there,

I’m currently trying to run a webhook to add a new hook and a new key on each new project, via a system webhook.

The hook creation via the API wasn’t a problem at all, but the key is more a problem to me

def createkey(project_id):
    data={}
    data["id"]='%s' % project_id
    data["title"]='%s' % title
    data['key']="%s" % key
    url='https://mygitlab.com/api/v3/projects/%s/keys' % (str(project_id))
    r = requests.post(url, '%s' % data, headers=headers)
    print url, data, r.status_code
    return r.status_code

It always returns a 400 HTTP code, I even tried with curl to debug and obtain the exact same thing :

curl  -H "content-type: application/json" -H "PRIVATE-TOKEN: mytoken" -H "Accept: application/json" -X POST --insecure https://mygitlabcom/api/v3/projects/$projectid/keys -d "{'key': 'ssh-rsa mykey root@myhost 'title': 'myname', 'id': '701'}"
{"status":"400","error":"Bad Request"}

n.b. : I am using the format presented here : http://tldrify.com/d35

bump ?

There is a pending MR which I’m working on and hopefully will finish this month https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/681

See if this curl example helps https://gitlab.com/gitlab-org/gitlab-ce/blob/75279cf206c17d185102d71780f83d47523781d2/doc/api/deploy_keys.md

Yeah the example helped me fix my issue :smile:

I was missing the trailing slash on the URL to hit and in Python I forgot to json.dump()

so the new snippet is :

def createkey(project_id):
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%dT%H:%M:%SZ')
    data={}
    data["title"]='%s' % title
    data['key']="%s" % key
    data=json.dumps(data)
    url='https://mygitlab.com/api/v3/projects/%s/keys/' % (str(project_id))
    r = requests.post(url, '%s' % data, headers=headers)
    print url, data, r.status_code
    return r.status_code
1 Like