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
2
  • 5
    Create a Python dictionary instead of the JSON and pass it as the json= argument to requests.post(). Commented Dec 15, 2020 at 10:23
  • 3
    Does this answer your question? Python Request Post with param data Commented Dec 15, 2020 at 10:23

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This Code work for me..Thanks :)
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}"} ] }'

1 Comment

this code give below "SyntaxError: f-string: expressions nested too deeply"
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))

3 Comments

make sure you have python version >3.6, if you are going to use this code
This gives me SyntaxError: f-string: expressions nested too deeply on Python 3.7
This code works for me..thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.