0
# Client Management
1
2
Central client configuration and authentication for accessing Linear's API with caching, connection management, and schema validation capabilities.
3
4
## Capabilities
5
6
### Client Initialization
7
8
The LinearClient serves as the main entry point, handling authentication, configuration, and resource manager initialization.
9
10
```python { .api }
11
class LinearClient:
12
def __init__(
13
self,
14
api_key: Optional[str] = None,
15
enable_cache: bool = True,
16
cache_ttl: int = 3600,
17
auto_unwrap_connections: bool = True,
18
):
19
"""
20
Initialize the Linear API client.
21
22
Args:
23
api_key: The Linear API key. If not provided, the LINEAR_API_KEY
24
environment variable will be used.
25
enable_cache: Whether to enable caching (default: True)
26
cache_ttl: Default time-to-live for cached items in seconds (default: 1 hour)
27
auto_unwrap_connections: Whether to automatically unwrap GraphQL connections (default: True)
28
29
Raises:
30
ValueError: If no API key is provided and LINEAR_API_KEY environment
31
variable is not set.
32
"""
33
```
34
35
Usage examples:
36
37
```python
38
from linear_api import LinearClient
39
40
# Using environment variable LINEAR_API_KEY
41
client = LinearClient()
42
43
# Explicit API key
44
client = LinearClient(api_key="your_api_key")
45
46
# Custom configuration
47
client = LinearClient(
48
api_key="your_api_key",
49
enable_cache=False,
50
cache_ttl=7200, # 2 hours
51
auto_unwrap_connections=False
52
)
53
```
54
55
### Direct API Access
56
57
Low-level GraphQL API access for advanced use cases or custom queries.
58
59
```python { .api }
60
def call_api(self, query: Dict[str, Any] | str) -> Dict[str, Any]:
61
"""
62
Call the Linear API with the provided query.
63
64
Args:
65
query: The GraphQL query or mutation to execute
66
67
Returns:
68
The API response data
69
70
Raises:
71
ValueError: If the API call fails
72
"""
73
74
def execute_graphql(self, query: str, variables: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
75
"""
76
Execute a GraphQL query with variables.
77
78
Args:
79
query: The GraphQL query string
80
variables: Optional variables for the query
81
82
Returns:
83
The API response data
84
"""
85
```
86
87
Usage examples:
88
89
```python
90
# Simple query
91
response = client.call_api({"query": "{ viewer { name email } }"})
92
93
# Query with variables
94
query = """
95
query GetIssue($id: String!) {
96
issue(id: $id) {
97
id
98
title
99
state { name }
100
}
101
}
102
"""
103
response = client.execute_graphql(query, {"id": "issue-id"})
104
```
105
106
### Cache Management
107
108
Control caching behavior for API responses to optimize performance and reduce API calls.
109
110
```python { .api }
111
def clear_cache(self, cache_name: Optional[str] = None) -> None:
112
"""
113
Clear cache data.
114
115
Args:
116
cache_name: Optional name of specific cache to clear. If None, clears all caches.
117
"""
118
```
119
120
Usage examples:
121
122
```python
123
# Clear all caches
124
client.clear_cache()
125
126
# Clear specific cache
127
client.clear_cache("issues")
128
129
# Access cache manager directly
130
client.cache.disable()
131
client.cache.enable()
132
print(client.cache.stats)
133
```
134
135
### Connection Unwrapping Control
136
137
Manage automatic GraphQL connection unwrapping for pagination handling.
138
139
```python { .api }
140
def enable_connection_unwrapping(self) -> None:
141
"""
142
Enable automatic unwrapping of GraphQL connections in all managers.
143
144
This settings improves usability by automatically handling pagination,
145
but may increase the number of API calls for large data sets.
146
"""
147
148
def disable_connection_unwrapping(self) -> None:
149
"""
150
Disable automatic unwrapping of GraphQL connections in all managers.
151
152
This setting reduces the number of API calls but requires manual
153
handling of pagination for large data sets.
154
"""
155
```
156
157
Usage examples:
158
159
```python
160
# Runtime control
161
client.enable_connection_unwrapping()
162
client.disable_connection_unwrapping()
163
164
# Check current managers
165
print(f"Issue manager unwrapping: {client.issues._auto_unwrap_connections}")
166
```
167
168
### Schema Validation
169
170
Validate domain models against the GraphQL schema for development and debugging.
171
172
```python { .api }
173
def validate_schema(self, model_class: type[LinearModel]) -> Dict[str, Dict[str, Any]]:
174
"""
175
Validate the domain models against the GraphQL schema.
176
177
Returns:
178
A dictionary mapping model names to validation results
179
"""
180
```
181
182
Usage examples:
183
184
```python
185
from linear_api import LinearIssue
186
187
# Validate specific model
188
validation_results = client.validate_schema(LinearIssue)
189
print(validation_results)
190
191
# Check for missing fields
192
if validation_results['missing_fields']:
193
print("Missing fields:", validation_results['missing_fields'])
194
```
195
196
### Manager Access
197
198
Access to specialized resource managers for different Linear entities.
199
200
```python { .api }
201
# Manager Properties (read-only)
202
cache: CacheManager # Cache management
203
issues: IssueManager # Issue operations
204
projects: ProjectManager # Project operations
205
teams: TeamManager # Team operations
206
users: UserManager # User operations
207
```
208
209
Usage examples:
210
211
```python
212
# Access managers
213
issue = client.issues.get("issue-id")
214
project = client.projects.get("project-id")
215
team = client.teams.get("team-id")
216
user = client.users.get("user-id")
217
218
# Manager operations
219
all_issues = client.issues.get_all()
220
team_projects = client.projects.get_all(team_id="team-id")
221
team_members = client.teams.get_members("team-id")
222
```
223
224
## Error Handling
225
226
The client provides comprehensive error handling for common scenarios:
227
228
```python
229
from linear_api import LinearClient
230
231
try:
232
# Missing API key
233
client = LinearClient()
234
except ValueError as e:
235
print(f"Authentication error: {e}")
236
237
try:
238
# Invalid query
239
client.call_api({"invalid": "query"})
240
except ValueError as e:
241
print(f"API error: {e}")
242
```
243
244
## Performance Optimization
245
246
### Caching Strategy
247
248
```python
249
# High-performance configuration for read-heavy workloads
250
client = LinearClient(
251
enable_cache=True,
252
cache_ttl=3600, # 1 hour cache
253
auto_unwrap_connections=True
254
)
255
256
# Memory-conscious configuration
257
client = LinearClient(
258
enable_cache=True,
259
cache_ttl=300, # 5 minute cache
260
auto_unwrap_connections=False # Manual pagination
261
)
262
```
263
264
### Connection Management
265
266
```python
267
# For large datasets, disable auto-unwrapping
268
client.disable_connection_unwrapping()
269
270
# Manually handle pagination when needed
271
issues_page = client.issues.get_by_team("team-name") # Returns first page only
272
```
273
274
## Authentication
275
276
The client supports multiple authentication methods:
277
278
### Environment Variable (Recommended)
279
280
```bash
281
export LINEAR_API_KEY="your_api_key_here"
282
```
283
284
```python
285
client = LinearClient() # Automatically uses environment variable
286
```
287
288
### Direct API Key
289
290
```python
291
client = LinearClient(api_key="your_api_key_here")
292
```
293
294
### Runtime Validation
295
296
```python
297
# Check if client is properly authenticated
298
try:
299
me = client.users.get_me()
300
print(f"Authenticated as: {me.name}")
301
except ValueError:
302
print("Authentication failed")
303
```