Shotgun API Tips and Tricks Megapost

Creating Notes that have Attachments

It’s a little janky to create Notes with Attachments via the API, but there is a way to do it. Props to @bouchep for the genesis on this one!

In order to create a note with an attachment in the body, the attachment has to already exist so that the Note creation can reference it properly. The issue is, and I’m sure you’ve noticed, that there’s no way to upload something without something already existing to link it to. Very frustrating for Note creation via the API! So one workaround is to keep a project-based dummy Version around to upload attachment/annotations to, so that they exist and have an id that the note creation process can reference. Here’s how I did it:

# create a project-based dummy version to upload attachments to,
# if one doesn't already exist
dummy = sg.find_one('Version', [['code','is','dummyVersion']])
if dummy == None:
    dummy = sg.create('Version', {'description':'dummy version to link files against','code':'dummyVersion','project':{'type':'Project','id':89}})

With this dummy Version in place, we can now proceed:

# find the version you want to attach a note to
version = sg.find_one('Version',[['id','is',6961]])

# upload a new Attachment to the dummy, the result is the id of the new Attachment
att_id = sg.upload('Version', dummy['id'],'magneto.jpg')
attachment = sg.find_one('Attachment', [['id','is',att_id]],['created_at'])

# this create call uses the attachment created just above
sg.create(
        'Note',
        {
            'project':{'id':89,'type':'Project'},
            'created_at':attachment['created_at'],
            'note_links':[version], #note_links expects an array of entity hashes
            'content':'new simultaneous upload test',
            'attachments':[{'type':'Attachment','id':att_id}]
            }
        )

Note in the example above that I’m using the created_at date from the Attachment in the Note. This is something we key on internally when displaying Notes. If the times don’t match, the attachment will look like a separate reply, even though it’s not. If we steal the creation date from the attachment and make that the date in the Note, then the file will look like it’s in the body of the original note (though it’ll say “Attachments” instead of “Annotations”). Note that you can specify creation date at the time of creation, but you can’t modify it after the fact, so be aware!

8 Likes