3

There is a cURL example in section Triggering a Build of TeamCity 9.x Documentation:

curl -v -u user:password http://teamcity.server.url:8111/app/rest/buildQueue --request POST --header "Content-Type:application/xml" --data-binary @build.xml

I'd like to know how to convert it into an equivalent Python script (using POST request from the requests module)?


BTW, I tried the following Python script but got such a response code 400 (Bad Request):

url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/json'}
data = json.dumps({'buildTypeId': 'MyTestBuild'})
r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)
print "r = ", r

>> r =  <Response [400]>

If change the Content-Type in headers into Accept, got another response code 415 (Unsupported Media Type):

headers = {'Accept': 'application/json'}

>> r =  <Response [415]>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zhongde Yu
  • 33
  • 1
  • 6

3 Answers3

2

The documentation for triggering a build shows you need to send XML, not JSON:

<build>
    <buildType id="buildConfID"/>
</build>

The TeamCity REST API is a bit of a mixed bag; some methods accept both XML and JSON, some only accept XML. This is one of those latter methods. They'll respond with either XML or JSON, based on what you set the Accept header to.

Send the above with your required build ID; for an XML document that simply you could use templating:

from xml.sax.saxutils import quoteattr

template = '<build><buildType id={id}/></build>'

url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/xml'}
build_id = 'MyTestBuild'
data = template.format(id=quoteattr(build_id))

r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)

Note that I used the xml.sax.saxutils.quotattr() function to make sure the value of build_id is properly quoted for inclusion as a XML attribute.

This'll produce XML; add 'Accept': 'application/json' to the headers dictionary if you want to process a JSON response.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

FYI json request works in TeamCity 10.

hryamzik
  • 849
  • 1
  • 9
  • 16
0

Since this question was written & answered, a contemporary OSS alternative now exists: pyteamcity.

Pip command to install (or add pyteamcity to requirements.txt, etc.)

pip install pyteamcity

Code:

from pyteamcity import TeamCity
tc = TeamCity('username', 'password', 'server', 'port')
result = tc.trigger_build('build_id')
print(f'Build triggered. Web URL: {result['webUrl']}')
Nick Giampietro
  • 178
  • 1
  • 8