Skip to content

client

Label Studio API Client - programmatic interface for Label Studio project and annotation management.

Provides HTTP client functionality for interacting with Label Studio server including project creation, task import, annotation export, and project management operations.

LabelStudioClient

HTTP client for Label Studio API providing programmatic access to annotation projects.

Handles authentication, request formatting, and response processing for all Label Studio operations including project management and annotation workflows.

Attributes:

Name Type Description
server_url

Base URL of the Label Studio server

api_token

Authentication token for API access

headers

HTTP headers including authorization and content type

Source code in rm_gallery/core/data/annotation/client.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class LabelStudioClient:
    """
    HTTP client for Label Studio API providing programmatic access to annotation projects.

    Handles authentication, request formatting, and response processing for all
    Label Studio operations including project management and annotation workflows.

    Attributes:
        server_url: Base URL of the Label Studio server
        api_token: Authentication token for API access
        headers: HTTP headers including authorization and content type
    """

    def __init__(self, server_url: str, api_token: str):
        """
        Initialize Label Studio client with server connection details.

        Args:
            server_url: Base URL of Label Studio server (e.g., http://localhost:8080)
            api_token: API authentication token from Label Studio user account
        """
        self.server_url = server_url
        self.api_token = api_token
        self.headers = {
            "Authorization": f"Token {api_token}",
            "Content-Type": "application/json",
        }

    def create_project(
        self, title: str, label_config: str, description: str = ""
    ) -> Optional[int]:
        """
        Create a new annotation project in Label Studio.

        Sets up a new project with specified labeling configuration and metadata
        for data annotation workflows.

        Args:
            title: Human-readable project title
            label_config: Label Studio XML configuration defining annotation interface
            description: Optional project description for documentation

        Returns:
            Project ID if creation successful, None if failed

        Raises:
            requests.RequestException: If HTTP request fails
        """
        try:
            project_data = {
                "title": title,
                "description": description,
                "label_config": label_config,
            }

            response = requests.post(
                f"{self.server_url}/api/projects/",
                json=project_data,
                headers=self.headers,
                timeout=30,
            )

            if response.status_code == 201:
                project = response.json()
                logger.info(f"Created project: {title} (ID: {project['id']})")
                return project["id"]
            else:
                logger.error(
                    f"Failed to create project: {response.status_code} - {response.text}"
                )
                return None

        except Exception as e:
            logger.error(f"Error creating project: {e}")
            return None

    def import_tasks(self, project_id: int, tasks: List[Dict[str, Any]]) -> bool:
        """
        Import annotation tasks to an existing project.

        Uploads data samples as tasks to be annotated within the specified project.
        Each task represents one item to be labeled by annotators.

        Args:
            project_id: Target project identifier
            tasks: List of task dictionaries containing data and metadata

        Returns:
            True if import successful, False otherwise

        Raises:
            requests.RequestException: If HTTP request fails
        """
        try:
            response = requests.post(
                f"{self.server_url}/api/projects/{project_id}/import",
                json=tasks,
                headers=self.headers,
                timeout=60,
            )

            if response.status_code == 201:
                logger.info(
                    f"Successfully imported {len(tasks)} tasks to project {project_id}"
                )
                return True
            else:
                logger.error(
                    f"Failed to import tasks: {response.status_code} - {response.text}"
                )
                return False

        except Exception as e:
            logger.error(f"Error importing tasks: {e}")
            return False

    def export_annotations(
        self, project_id: int, export_type: str = "JSON"
    ) -> Optional[List[Dict[str, Any]]]:
        """
        Export completed annotations from a project.

        Retrieves all annotation data from the project for analysis and
        downstream processing in reward model training pipelines.

        Args:
            project_id: Source project identifier
            export_type: Export format (JSON, CSV, etc.)

        Returns:
            List of annotation dictionaries if export successful, None otherwise

        Raises:
            requests.RequestException: If HTTP request fails
        """
        try:
            response = requests.get(
                f"{self.server_url}/api/projects/{project_id}/export",
                params={"exportType": export_type},
                headers=self.headers,
                timeout=60,
            )

            if response.status_code == 200:
                annotations = response.json()
                logger.info(
                    f"Exported {len(annotations)} annotations from project {project_id}"
                )
                return annotations
            else:
                logger.error(f"Failed to export annotations: {response.status_code}")
                return None

        except Exception as e:
            logger.error(f"Error exporting annotations: {e}")
            return None

    def delete_project(self, project_id: int) -> bool:
        """
        Delete an annotation project and all associated data.

        Permanently removes project, tasks, and annotations. Use with caution
        as this operation cannot be undone.

        Args:
            project_id: Project identifier to delete

        Returns:
            True if deletion successful, False otherwise

        Raises:
            requests.RequestException: If HTTP request fails
        """
        try:
            response = requests.delete(
                f"{self.server_url}/api/projects/{project_id}/",
                headers=self.headers,
                timeout=30,
            )

            if response.status_code == 204:
                logger.info(f"Successfully deleted project {project_id}")
                return True
            else:
                logger.error(f"Failed to delete project: {response.status_code}")
                return False

        except Exception as e:
            logger.error(f"Error deleting project: {e}")
            return False

    def get_projects(self) -> Optional[List[Dict[str, Any]]]:
        """
        Retrieve list of all accessible projects.

        Returns metadata for all projects accessible to the current user
        for project discovery and management operations.

        Returns:
            List of project dictionaries with metadata if successful, None otherwise

        Raises:
            requests.RequestException: If HTTP request fails
        """
        try:
            response = requests.get(
                f"{self.server_url}/api/projects/",
                headers=self.headers,
                timeout=30,
            )

            if response.status_code == 200:
                projects = response.json()
                logger.info(f"Retrieved {len(projects)} projects")
                return projects
            else:
                logger.error(f"Failed to get projects: {response.status_code}")
                return None

        except Exception as e:
            logger.error(f"Error getting projects: {e}")
            return None

__init__(server_url, api_token)

Initialize Label Studio client with server connection details.

Parameters:

Name Type Description Default
server_url str

Base URL of Label Studio server (e.g., http://localhost:8080)

required
api_token str

API authentication token from Label Studio user account

required
Source code in rm_gallery/core/data/annotation/client.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def __init__(self, server_url: str, api_token: str):
    """
    Initialize Label Studio client with server connection details.

    Args:
        server_url: Base URL of Label Studio server (e.g., http://localhost:8080)
        api_token: API authentication token from Label Studio user account
    """
    self.server_url = server_url
    self.api_token = api_token
    self.headers = {
        "Authorization": f"Token {api_token}",
        "Content-Type": "application/json",
    }

create_project(title, label_config, description='')

Create a new annotation project in Label Studio.

Sets up a new project with specified labeling configuration and metadata for data annotation workflows.

Parameters:

Name Type Description Default
title str

Human-readable project title

required
label_config str

Label Studio XML configuration defining annotation interface

required
description str

Optional project description for documentation

''

Returns:

Type Description
Optional[int]

Project ID if creation successful, None if failed

Raises:

Type Description
RequestException

If HTTP request fails

Source code in rm_gallery/core/data/annotation/client.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def create_project(
    self, title: str, label_config: str, description: str = ""
) -> Optional[int]:
    """
    Create a new annotation project in Label Studio.

    Sets up a new project with specified labeling configuration and metadata
    for data annotation workflows.

    Args:
        title: Human-readable project title
        label_config: Label Studio XML configuration defining annotation interface
        description: Optional project description for documentation

    Returns:
        Project ID if creation successful, None if failed

    Raises:
        requests.RequestException: If HTTP request fails
    """
    try:
        project_data = {
            "title": title,
            "description": description,
            "label_config": label_config,
        }

        response = requests.post(
            f"{self.server_url}/api/projects/",
            json=project_data,
            headers=self.headers,
            timeout=30,
        )

        if response.status_code == 201:
            project = response.json()
            logger.info(f"Created project: {title} (ID: {project['id']})")
            return project["id"]
        else:
            logger.error(
                f"Failed to create project: {response.status_code} - {response.text}"
            )
            return None

    except Exception as e:
        logger.error(f"Error creating project: {e}")
        return None

delete_project(project_id)

Delete an annotation project and all associated data.

Permanently removes project, tasks, and annotations. Use with caution as this operation cannot be undone.

Parameters:

Name Type Description Default
project_id int

Project identifier to delete

required

Returns:

Type Description
bool

True if deletion successful, False otherwise

Raises:

Type Description
RequestException

If HTTP request fails

Source code in rm_gallery/core/data/annotation/client.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def delete_project(self, project_id: int) -> bool:
    """
    Delete an annotation project and all associated data.

    Permanently removes project, tasks, and annotations. Use with caution
    as this operation cannot be undone.

    Args:
        project_id: Project identifier to delete

    Returns:
        True if deletion successful, False otherwise

    Raises:
        requests.RequestException: If HTTP request fails
    """
    try:
        response = requests.delete(
            f"{self.server_url}/api/projects/{project_id}/",
            headers=self.headers,
            timeout=30,
        )

        if response.status_code == 204:
            logger.info(f"Successfully deleted project {project_id}")
            return True
        else:
            logger.error(f"Failed to delete project: {response.status_code}")
            return False

    except Exception as e:
        logger.error(f"Error deleting project: {e}")
        return False

export_annotations(project_id, export_type='JSON')

Export completed annotations from a project.

Retrieves all annotation data from the project for analysis and downstream processing in reward model training pipelines.

Parameters:

Name Type Description Default
project_id int

Source project identifier

required
export_type str

Export format (JSON, CSV, etc.)

'JSON'

Returns:

Type Description
Optional[List[Dict[str, Any]]]

List of annotation dictionaries if export successful, None otherwise

Raises:

Type Description
RequestException

If HTTP request fails

Source code in rm_gallery/core/data/annotation/client.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def export_annotations(
    self, project_id: int, export_type: str = "JSON"
) -> Optional[List[Dict[str, Any]]]:
    """
    Export completed annotations from a project.

    Retrieves all annotation data from the project for analysis and
    downstream processing in reward model training pipelines.

    Args:
        project_id: Source project identifier
        export_type: Export format (JSON, CSV, etc.)

    Returns:
        List of annotation dictionaries if export successful, None otherwise

    Raises:
        requests.RequestException: If HTTP request fails
    """
    try:
        response = requests.get(
            f"{self.server_url}/api/projects/{project_id}/export",
            params={"exportType": export_type},
            headers=self.headers,
            timeout=60,
        )

        if response.status_code == 200:
            annotations = response.json()
            logger.info(
                f"Exported {len(annotations)} annotations from project {project_id}"
            )
            return annotations
        else:
            logger.error(f"Failed to export annotations: {response.status_code}")
            return None

    except Exception as e:
        logger.error(f"Error exporting annotations: {e}")
        return None

get_projects()

Retrieve list of all accessible projects.

Returns metadata for all projects accessible to the current user for project discovery and management operations.

Returns:

Type Description
Optional[List[Dict[str, Any]]]

List of project dictionaries with metadata if successful, None otherwise

Raises:

Type Description
RequestException

If HTTP request fails

Source code in rm_gallery/core/data/annotation/client.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def get_projects(self) -> Optional[List[Dict[str, Any]]]:
    """
    Retrieve list of all accessible projects.

    Returns metadata for all projects accessible to the current user
    for project discovery and management operations.

    Returns:
        List of project dictionaries with metadata if successful, None otherwise

    Raises:
        requests.RequestException: If HTTP request fails
    """
    try:
        response = requests.get(
            f"{self.server_url}/api/projects/",
            headers=self.headers,
            timeout=30,
        )

        if response.status_code == 200:
            projects = response.json()
            logger.info(f"Retrieved {len(projects)} projects")
            return projects
        else:
            logger.error(f"Failed to get projects: {response.status_code}")
            return None

    except Exception as e:
        logger.error(f"Error getting projects: {e}")
        return None

import_tasks(project_id, tasks)

Import annotation tasks to an existing project.

Uploads data samples as tasks to be annotated within the specified project. Each task represents one item to be labeled by annotators.

Parameters:

Name Type Description Default
project_id int

Target project identifier

required
tasks List[Dict[str, Any]]

List of task dictionaries containing data and metadata

required

Returns:

Type Description
bool

True if import successful, False otherwise

Raises:

Type Description
RequestException

If HTTP request fails

Source code in rm_gallery/core/data/annotation/client.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def import_tasks(self, project_id: int, tasks: List[Dict[str, Any]]) -> bool:
    """
    Import annotation tasks to an existing project.

    Uploads data samples as tasks to be annotated within the specified project.
    Each task represents one item to be labeled by annotators.

    Args:
        project_id: Target project identifier
        tasks: List of task dictionaries containing data and metadata

    Returns:
        True if import successful, False otherwise

    Raises:
        requests.RequestException: If HTTP request fails
    """
    try:
        response = requests.post(
            f"{self.server_url}/api/projects/{project_id}/import",
            json=tasks,
            headers=self.headers,
            timeout=60,
        )

        if response.status_code == 201:
            logger.info(
                f"Successfully imported {len(tasks)} tasks to project {project_id}"
            )
            return True
        else:
            logger.error(
                f"Failed to import tasks: {response.status_code} - {response.text}"
            )
            return False

    except Exception as e:
        logger.error(f"Error importing tasks: {e}")
        return False