'trello API add label to card in python

I have a trello board with a list, created some cards with python and labels manually. I'm able to get card_id's and label id`s using python.

But I do not understand how to add an existing label to an existing card. Sample code at API description is:

import requests
url = "https://api.trello.com/1/cards/{id}/idLabels"

query = {
   'key': 'APIKey',
   'token': 'APIToken'
}

response = requests.request(
   "POST",
   url,
   params=query
)

I tried:

main_trello_endpoint = "https://api.trello.com/1/"

def add_label_to_card(card_id, label_id):
    add_label_endpoint = main_trello_endpoint+"cards/"+card_id+"/"+label_id
    querystring =  {"key":trello_key,"token": trello_token}
    response = requests.post(add_label_endpoint, params= querystring)
    return response

add_label_to_card(existing_card_id, existing_label_id))

response is 404 What is the misunderstanding on my side?



Solution 1:[1]

The url you send your request to + your request method are incorrect.

Apparently there is an endpoint to do this the way you do it, excuse me.


You need to send a PUT request with the idLabels as a parameter in the put data.

https://developer.atlassian.com/cloud/trello/rest/api-group-cards/#api-cards-id-put

You need to use request.put with the label object itself + the label ids you want

data = {
    **current_label,
    "idLabels": ",".join(current_label.idLabels + [new_label_ids])
}
request.put("trello_api/cards/card-id/", data=data, params=querystring)

For the endpoint you posted your url seems to be wrong. It only takes a card id and you need to post the value as a query param. (Which is very absurd but it is what it is)

def add_label_to_card(card_id, label_id):
    url = f"https://api.trello.com/1/cards/{card_id}/idLabels"
    params = {**auth_params, "value": label_id}
    response = request.post(url, params=params)
    # preferably some cleanup and status checks
    return ...

If this doesn't work also, try putting data={"value": label_id} to the same url

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1