Skip to content

Commit f3b7b88

Browse files
dnicholdnichol
authored andcommitted
Example creating an API token
1 parent c6835c7 commit f3b7b88

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

examples/create_api_token.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
'''
2+
Created on January 1, 2024
3+
4+
@author: dnichol
5+
6+
Create a new user
7+
8+
To use this script. Firstly create a .restconfig.json file with either API token or basic auth (username/password) as per the examples :
9+
https://github.com/blackducksoftware/hub-rest-api-python/blob/master/restconfig.json.example
10+
https://github.com/blackducksoftware/hub-rest-api-python/blob/master/restconfig.json.api_token.example
11+
12+
Then to run:
13+
python create_api_token.py MyToken "My Token Description"
14+
15+
It will output the token that is generated. If you would like the token to be read only add the -r flag to the command line.
16+
17+
'''
18+
import argparse
19+
import json
20+
import logging
21+
from pprint import pprint
22+
import sys
23+
24+
from blackduck.HubRestApi import HubInstance
25+
26+
27+
parser = argparse.ArgumentParser("Create an API token")
28+
parser.add_argument("name")
29+
parser.add_argument("description")
30+
parser.add_argument("-r", "--readonly", action='store_true')
31+
32+
33+
args = parser.parse_args()
34+
35+
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
36+
logging.getLogger("requests").setLevel(logging.WARNING)
37+
logging.getLogger("urllib3").setLevel(logging.WARNING)
38+
39+
hub = HubInstance()
40+
41+
scope = ["read"]
42+
43+
if not args.readonly :
44+
scope = ["read", "write"]
45+
46+
post_data = {
47+
"name" : args.name,
48+
"description" : args.description,
49+
"scopes" : scope
50+
}
51+
52+
current_user = hub.get_current_user()
53+
add_token_url = hub.get_link(current_user, "api-tokens")
54+
55+
response = hub.execute_post(add_token_url, data=post_data)
56+
if response.status_code == 201:
57+
token_obj = response.json()
58+
token=token_obj['token']
59+
logging.info("Added API token {} = {}".format(args.name, token))
60+
else:
61+
logging.error("Failed to add API token {}, status code was {}".format(
62+
args.name, response.status_code))
63+
64+
65+
66+
67+

0 commit comments

Comments
 (0)