mstringer
mstringer

Reputation: 2302

How to get/set Trello custom fields using the API?

I'm already in love with the Custom Fields feature in Trello. Is there a way to get and set custom fields via the API?

I tried using the get field API call to get a field (on a board with a custom field defined called "MyCustomField"):

curl "https://api.trello.com/1/cards/57c473503a5ef0b76fddd0e5/MyCustomField?key=${TRELLO_API_KEY}&token=${TRELLO_OAUTH_TOKEN}"

to no avail.

Upvotes: 15

Views: 13763

Answers (3)

Employee
Employee

Reputation: 2411

The Custom Fields API from Trello is now officially available (announcement blog post here).

It allows users to manipulate both custom field items of boards and custom field item values on cards.

Custom Fields API documentation

Getting customFieldItems For Cards

Setting & Updating CustomFieldItems

Upvotes: 5

Alon Sabi
Alon Sabi

Reputation: 31

This is just to add to bdwakefield's answer. His solution involves hard coding the names of the field ids.

If you want to also retrieve the name of the fields themselves (for example get that "ZIn76ljn-4yeYvz" is actually "priority" in Trello, without needing to hard code it, call the following end point:

boards/{trello board id}/pluginData

This will return an array with the plugins information and in one of the array items, it will include a line along the lines of:

[value] => {"fields":[{"n":"~custom field name~:","t":0,"b":1,"id":"~custom field id that is the weird stuff at the card level~","friendlyType":"Text"}]}

So you just need to figure out the plugin for custom fields in your case, and you can retrieve the key -> value pair for the custom field name and the id associated with it.

It means that if you add / remove fields, or rename them, you can handle it at run time vs changing your code.

This will also give you the options for the custom field (when it is a dropdown like in bdwakefield's example above).

Upvotes: 3

bdwakefield
bdwakefield

Reputation: 705

So I have a "sort of" answer to this. It requires some hackery on your part to make it work and there is more than a little manual upkeep as you add properties or values -- but it works.

I am doing this in powershell (I am NOT well versed in ps just yet and this my first really 'big' script that I have pulled together for it) since my intent is to use this with TFS Builds to automate moving some cards around and creating release notes. We are using custom fields to help us classify the card and note estimate/actual hours etc. I used this guys work as a basis for my own scripting. I am not including everything but you should be able to piece everything together.

I have left out everything with connecting to Trello and all that. I have a bunch of other functions for gettings lists, moving cards, adding comments etc. The ps module I linked above has a lot of that built in as well.

function Get-TrelloCardPluginData
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory,ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [Alias('Id')]
        [string]$CardId

    )
    begin
    {
        $ErrorActionPreference = 'Stop'
    }
    process
    {
        try
        {
            $uri = "$baseUrl/cards/$CardId/pluginData?$($trelloConfig.String)"
            $result = Invoke-RestMethod -Uri $uri -Method GET
            return $result
        }
        catch
        {
            Write-Error $_.Exception.Message
        }
    }
}

You'll get data that looks like this:

@{id=582b5ec8df1572e572411513; idPlugin=56d5e249a98895a9797bebb9; scope=card; idModel=58263201749710ed3c706bef; value={"fields":{"ZIn76ljn-4yeYvz":2,"ZIn76ljn-c2yhZH":1}}; access=shared}

@{id=5834536fcff0525f26f9e53b; idPlugin=56d5e249a98895a9797bebb9; scope=card; idModel=567031ea6a01f722978b795d; value={"fields":{"ZIn76ljn-4yeYvz":4,"ZIn76ljn-c2yhZH":3}}; access=shared}

The fields collection is basically key/pair. The random characters correspond to the property and the value after that is what was set on the custom property. In this case it is an 'index' for the value in the dropdown. These two fields have a 'priority' (low, medium, high) and a 'classification' (Bug, Change Request, etc) for us. (We are using labels for something else).

So you'll have to create another fucntion where you can parse this data out. I am sure there are better ways to do it -- but this is what I have now:

function Get-TrelloCustomPropertyData($propertyData)
{
    $data = $propertyData.Replace('{"fields":{', '')
    $data = $data.Replace('}}', '')
    $data = $data.Replace('"', '')
    $sepone = ","
    $septwo = ":"
    $options = [System.StringSplitOptions]::RemoveEmptyEntries
    $obj = $data.Split($sepone, $options)

    $cardCustomFields = Get-TrelloCustomFieldObject

    foreach($pair in $obj)
    {
        $field = $pair.Split($septwo,$options)

        if (-Not [string]::IsNullOrWhiteSpace($field[0].Trim()))
        {
            switch($field[0].Trim())
            {
                'ZIn76ljn-4yeYvz' {
                    switch($field[1].Trim())
                    {
                        '1'{
                            $cardCustomFields.Priority = "Critical"
                        }
                        '2'{
                            $cardCustomFields.Priority = "High"
                        }
                        '3'{
                            $cardCustomFields.Priority = "Medium"
                        }
                        '4'{
                            $cardCustomFields.Priority = "Low"
                        }
                    }
                }
                'ZIn76ljn-c2yhZH' {
                    switch($field[1].Trim())
                    {
                        '1'{
                            $cardCustomFields.Classification = "Bug"
                        }
                        '2'{
                            $cardCustomFields.Classification = "Change Request"
                        }
                        '3'{
                            $cardCustomFields.Classification = "New Development"
                        }
                    }
                }
                'ZIn76ljn-uJyxzA'{$cardCustomFields.Estimated = $field[1].Trim()}
                'ZIn76ljn-AwYurD'{$cardCustomFields.Actual = $field[1].Trim()}
            }
        }
    }

    return $cardCustomFields
}

Get-TrelloCustomFieldObject is another ps function that I set up to build an object based on the properties I know that I have defined.

function Get-TrelloCustomFieldObject
{
    [CmdletBinding()]
    param()
    begin
    {
        $ErrorActionPreference = 'Stop'
    }
    process
    {
        $ccf = New-Object System.Object
        $ccf | Add-Member -type NoteProperty -name Priority -value "None"
        $ccf | Add-Member -type NoteProperty -name Classification -value "None"
        $ccf | Add-Member -type NoteProperty -name Estimated -value ""
        $ccf | Add-Member -type NoteProperty -name Actual -value ""
        return $ccf
    }
}

Upvotes: 2

Related Questions