#API add assets to albums

1 messages · Page 1 of 1 (latest)

static stone
#

I created a album but after i want to add a picture but here its the error:
{'message': ['each value in ids must be a UUID'], 'error': 'Bad Request', 'statusCode': 400}
Code:
def update_album(albumId, assetsIds):
global headers
data = {
"ids": [
assetsIds
]
}

headers['Content-Type'] = 'application/json'
response = requests.put(f'{IMMICH_URI}/api/album/{albumId}/assets', headers=headers, json=data)

return response.json()
nova shellBOT
#

:wave: Hey @static stone,

Thanks for reaching out to us. Please follow the recommended actions below; this will help us be more effective in our support effort and leave more time for building Immich :immich:.

References

Checklist

  1. :blue_square: I have verified I'm on the latest release(note that mobile app releases may take some time).
  2. :blue_square: I have read applicable release notes.
  3. :blue_square: I have reviewed the FAQs for known issues.
  4. :blue_square: I have reviewed Github for known issues.
  5. :blue_square: I have tried accessing Immich via local ip (without a custom reverse proxy).
  6. :blue_square: I have uploaded the relevant logs, docker compose, and .env files using the buttons below or the /upload command.
  7. :blue_square: I have tried an incognito window, disabled extensions, cleared mobile app cache, logged out and back in, different browsers, etc. as applicable

(an item can be marked as "complete" by reacting with the appropriate number)

If this ticket can be closed you can use the /close command, and re-open it later if needed.

static stone
#
import json

from dotenv import load_dotenv
from datetime import datetime
from pprint import pprint
import requests
import os

load_dotenv()

IMMICH_URI = os.getenv("IMMICH_URI")
IMMICH_API_KEY = os.getenv("IMMICH_API_KEY")
UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER")

headers = {
    'Accept': 'application/json',
    'x-api-key': IMMICH_API_KEY
}

listImages = []


def upload_image(file):
    stats = os.stat(file)
    data = {
        'deviceAssetId': f'{file}-{stats.st_mtime}',
        'deviceId': 'script',
        'fileCreatedAt': datetime.fromtimestamp(stats.st_mtime),
        'fileModifiedAt': datetime.fromtimestamp(stats.st_mtime),
        'isFavorite': 'false'
    }

    files = {
        'assetData': open(file, 'rb')
    }

    response = requests.post(f'{IMMICH_URI}/api/asset/upload', headers=headers, data=data, files=files)

    return response.json()


def check_album(title):
    response = requests.get(f'{IMMICH_URI}/api/album', headers=headers)
    for album in response.json():
        if album['albumName'] == title:
            return album['albumName'] == title, album['id']
    return 'Not found'
#
def create_album(title, assetsIds):
    data = {
        "albumName": title,
        "assetIds": assetsIds
    }

    response = requests.post(f'{IMMICH_URI}/api/album', headers=headers, json=data)

    return response.json()


def update_album(albumId, assetsIds):
    global headers
    data = {
        "ids": [
            assetsIds
        ]
    }

    headers['Content-Type'] = 'application/json'
    response = requests.put(f'{IMMICH_URI}/api/album/{albumId}/assets', headers=headers, json=data)

    return response.json()


def list_folders():
    folders = []
    for element in os.listdir(UPLOAD_FOLDER):
        if os.path.isdir(f"{UPLOAD_FOLDER}/{element}"):
            folders.append(element)
    return folders


def list_files(folder):
    files = []
    for element in os.listdir(f"{UPLOAD_FOLDER}/{folder}"):
        if os.path.isfile(f"{UPLOAD_FOLDER}/{folder}/{element}"):
            files.append(element)
    return files
#
def test():
    folders = list_folders()
    for folder in folders:
        files = list_files(folder)
        for file in files:
            infos = upload_image(f"{UPLOAD_FOLDER}/{folder}/{file}")
            listImages.append(infos)
        exists, album_id = check_album(folder)
        if exists:
            print(f"{folder} album exists")
            for image in listImages:
                if not image['duplicate']:
                    print(f"{update_album(album_id, [image['id']])}, added {image['id']}")
        else:
            print(f"{folder} album doesn't exist")
            print(f"{create_album(folder, listImages)}, created with {len(listImages)} images")
        listImages.clear()


if __name__ == '__main__':
    test()
surreal forum
#

Have you tried printing the json you're sending to debug?

static stone
#

Nope

#

its a dict and he has {"ids":[["ID"]]}

#

i will dumps this to create a real json

surreal forum
static stone
#

ok

#

new error

#

{"ids": ["e4e4e223-c5cb-4c0d-948a-11fc5bd8d49e"]}
<class 'str'>
{'message': 'Unexpected token '"', ""{\"ids\":"... is not valid JSON', 'error': 'Bad Request', 'statusCode': 400}

#

But i dumps it

#

like it done on the api docs

#
def update_album(albumId, assetsIds):
    global headers
    data = json.dumps({
        "ids": [
            assetsIds
        ]
    })

    print(data)
    print(type(data))

    headers['Content-Type'] = 'application/json'
    response = requests.put(f'{IMMICH_URI}/api/album/{albumId}/assets', headers=headers, json=data)

    return response.json()
surreal forum
#

If you're passing it to requests as json= then you shouldn't dumps it

static stone
#

ok

#

Work

#

Thanks

static stone
#

The API can handle how many requests per seconde ?

surreal forum
#

We've never tested, but it'd depend on many factors including the system you're running on etc

hollow escarp
#

If you have a decent system probably a lot though. I don't think services like immich-go have any limitation in place

static stone
#

No its a cheap hardware and i want to upload like 10000 files and manage them

#

so i will make a delay of 5s for each folder

hollow escarp
#

Then just use immich go or the offiicial immich cli

static stone
#

immich go ?

hollow escarp
#

#immich-go

static stone
#

its not zip folder

#

i will check it

hollow escarp
#

That doesn't matter

#

About specific details you can also ask in that channel, Simulot is quite active as well

static stone
#

ok

static stone
#

Hello, The api has a fuction to check if a assets is in a specific album ?

latent mortar
static stone
#

Lets go

spice hedge
#

There is a dedicated endpoint to add assets by IDs.

spice hedge
static stone
#

Nice