1

I had created a simple python program to send Post Api request using request module

# importing the requests library 
import requests 
import json


headers = {
    'PRIVATE-TOKEN': 'XXXXXXXXXXXXX',
    'Content-Type': 'application/json',
}

data = '{ "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": "failed"} ] }'

response = requests.post('https://gitlab.kazan.atosworldline.com/api/v4/projects/28427/pipeline', headers=headers, data=data)
print(response)

However, I wish to replace the below string to use a variable

"value": "failed"

something to below

"value": deployment_status
  • 5
    Create a Python dictionary instead of the JSON and pass it as the `json=` argument to `requests.post()`. – Klaus D. Dec 15 '20 at 10:23
  • 3
    Does this answer your question? [Python Request Post with param data](https://stackoverflow.com/questions/15900338/python-request-post-with-param-data) – Aven Desta Dec 15 '20 at 10:23

3 Answers3

1

If you want to pass json data to your API, you can directly use the json attribute of the request.post() function with a dictionary variable.

Example:

# importing the requests library 
import requests 


headers = {
    'PRIVATE-TOKEN': 'XXXXXXXXXXXXX',
    'Content-Type': 'application/json',
}
deployment_status = "failed"
data = { "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": deployment_status} ] }

response = requests.post('https://gitlab.kazan.atosworldline.com/api/v4/projects/28427/pipeline', headers=headers, json=data)
print(response)
Harshana
  • 5,151
  • 1
  • 17
  • 27
0

If you have a recent version of python you can use f-strings:

deployment_status = 'failed'
data = f'{ "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": "{deployment_status}"} ] }'

Update:

Ok, so that turned out to be too deeply nested for f-strings.

Better just to use json:

import json

deployment_status = 'failed'
data = {"ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": deployment_status} ] }

print(json.dumps(data))
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

You can use an "f-string" to format the value of the variable into your data string.

Example

deployment_status = 'status'
data = f'{ "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": "{deployment_status}"} ] }'
4RJ
  • 125
  • 2
  • 8