TypeSpec API Operations

TypeSpec API Operations

Shows how to add GET, POST, PATCH and DELETE operations to a TypeSpec API plugin for Microsoft 365 Copilot, with routing, parameters and adaptive cards.

Skill files1 file
SKILL.md419 lines
1
---
2
name: typespec-api-operations
3
description: 'Add GET, POST, PATCH, and DELETE operations to a TypeSpec API plugin with proper routing, parameters, and adaptive cards'
4
---
5
6
# Add TypeSpec API Operations
7
8
Add RESTful operations to an existing TypeSpec API plugin for Microsoft 365 Copilot.
9
10
## Adding GET Operations
11
12
### Simple GET - List All Items
13
```typescript
14
/**
15
* List all items.
16
*/
17
@route("/items")
18
@get op listItems(): Item[];
19
```
20
21
### GET with Query Parameter - Filter Results
22
```typescript
23
/**
24
* List items filtered by criteria.
25
* @param userId Optional user ID to filter items
26
*/
27
@route("/items")
28
@get op listItems(@query userId?: integer): Item[];
29
```
30
31
### GET with Path Parameter - Get Single Item
32
```typescript
33
/**
34
* Get a specific item by ID.
35
* @param id The ID of the item to retrieve
36
*/
37
@route("/items/{id}")
38
@get op getItem(@path id: integer): Item;
39
```
40
41
### GET with Adaptive Card
42
```typescript
43
/**
44
* List items with adaptive card visualization.
45
*/
46
@route("/items")
47
@card(#{
48
dataPath: "$",
49
title: "$.title",
50
file: "item-card.json"
51
})
52
@get op listItems(): Item[];
53
```
54
55
**Create the Adaptive Card** (`appPackage/item-card.json`):
56
```json
57
{
58
"type": "AdaptiveCard",
59
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
60
"version": "1.5",
61
"body": [
62
{
63
"type": "Container",
64
"$data": "${$root}",
65
"items": [
66
{
67
"type": "TextBlock",
68
"text": "**${if(title, title, 'N/A')}**",
69
"wrap": true
70
},
71
{
72
"type": "TextBlock",
73
"text": "${if(description, description, 'N/A')}",
74
"wrap": true
75
}
76
]
77
}
78
],
79
"actions": [
80
{
81
"type": "Action.OpenUrl",
82
"title": "View Details",
83
"url": "https://example.com/items/${id}"
84
}
85
]
86
}
87
```
88
89
## Adding POST Operations
90
91
### Simple POST - Create Item
92
```typescript
93
/**
94
* Create a new item.
95
* @param item The item to create
96
*/
97
@route("/items")
98
@post op createItem(@body item: CreateItemRequest): Item;
99
100
model CreateItemRequest {
101
title: string;
102
description?: string;
103
userId: integer;
104
}
105
```
106
107
### POST with Confirmation
108
```typescript
109
/**
110
* Create a new item with confirmation.
111
*/
112
@route("/items")
113
@post
114
@capabilities(#{
115
confirmation: #{
116
type: "AdaptiveCard",
117
title: "Create Item",
118
body: """
119
Are you sure you want to create this item?
120
* **Title**: {{ function.parameters.item.title }}
121
* **User ID**: {{ function.parameters.item.userId }}
122
"""
123
}
124
})
125
op createItem(@body item: CreateItemRequest): Item;
126
```
127
128
## Adding PATCH Operations
129
130
### Simple PATCH - Update Item
131
```typescript
132
/**
133
* Update an existing item.
134
* @param id The ID of the item to update
135
* @param item The updated item data
136
*/
137
@route("/items/{id}")
138
@patch op updateItem(
139
@path id: integer,
140
@body item: UpdateItemRequest
141
): Item;
142
143
model UpdateItemRequest {
144
title?: string;
145
description?: string;
146
status?: "active" | "completed" | "archived";
147
}
148
```
149
150
### PATCH with Confirmation
151
```typescript
152
/**
153
* Update an item with confirmation.
154
*/
155
@route("/items/{id}")
156
@patch
157
@capabilities(#{
158
confirmation: #{
159
type: "AdaptiveCard",
160
title: "Update Item",
161
body: """
162
Updating item #{{ function.parameters.id }}:
163
* **Title**: {{ function.parameters.item.title }}
164
* **Status**: {{ function.parameters.item.status }}
165
"""
166
}
167
})
168
op updateItem(
169
@path id: integer,
170
@body item: UpdateItemRequest
171
): Item;
172
```
173
174
## Adding DELETE Operations
175
176
### Simple DELETE
177
```typescript
178
/**
179
* Delete an item.
180
* @param id The ID of the item to delete
181
*/
182
@route("/items/{id}")
183
@delete op deleteItem(@path id: integer): void;
184
```
185
186
### DELETE with Confirmation
187
```typescript
188
/**
189
* Delete an item with confirmation.
190
*/
191
@route("/items/{id}")
192
@delete
193
@capabilities(#{
194
confirmation: #{
195
type: "AdaptiveCard",
196
title: "Delete Item",
197
body: """
198
⚠️ Are you sure you want to delete item #{{ function.parameters.id }}?
199
This action cannot be undone.
200
"""
201
}
202
})
203
op deleteItem(@path id: integer): void;
204
```
205
206
## Complete CRUD Example
207
208
### Define the Service and Models
209
```typescript
210
@service
211
@server("https://api.example.com")
212
@actions(#{
213
nameForHuman: "Items API",
214
descriptionForHuman: "Manage items",
215
descriptionForModel: "Read, create, update, and delete items"
216
})
217
namespace ItemsAPI {
218
219
// Models
220
model Item {
221
@visibility(Lifecycle.Read)
222
id: integer;
223
224
userId: integer;
225
title: string;
226
description?: string;
227
status: "active" | "completed" | "archived";
228
229
@format("date-time")
230
createdAt: utcDateTime;
231
232
@format("date-time")
233
updatedAt?: utcDateTime;
234
}
235
236
model CreateItemRequest {
237
userId: integer;
238
title: string;
239
description?: string;
240
}
241
242
model UpdateItemRequest {
243
title?: string;
244
description?: string;
245
status?: "active" | "completed" | "archived";
246
}
247
248
// Operations
249
@route("/items")
250
@card(#{ dataPath: "$", title: "$.title", file: "item-card.json" })
251
@get op listItems(@query userId?: integer): Item[];
252
253
@route("/items/{id}")
254
@card(#{ dataPath: "$", title: "$.title", file: "item-card.json" })
255
@get op getItem(@path id: integer): Item;
256
257
@route("/items")
258
@post
259
@capabilities(#{
260
confirmation: #{
261
type: "AdaptiveCard",
262
title: "Create Item",
263
body: "Creating: **{{ function.parameters.item.title }}**"
264
}
265
})
266
op createItem(@body item: CreateItemRequest): Item;
267
268
@route("/items/{id}")
269
@patch
270
@capabilities(#{
271
confirmation: #{
272
type: "AdaptiveCard",
273
title: "Update Item",
274
body: "Updating item #{{ function.parameters.id }}"
275
}
276
})
277
op updateItem(@path id: integer, @body item: UpdateItemRequest): Item;
278
279
@route("/items/{id}")
280
@delete
281
@capabilities(#{
282
confirmation: #{
283
type: "AdaptiveCard",
284
title: "Delete Item",
285
body: "⚠️ Delete item #{{ function.parameters.id }}?"
286
}
287
})
288
op deleteItem(@path id: integer): void;
289
}
290
```
291
292
## Advanced Features
293
294
### Multiple Query Parameters
295
```typescript
296
@route("/items")
297
@get op listItems(
298
@query userId?: integer,
299
@query status?: "active" | "completed" | "archived",
300
@query limit?: integer,
301
@query offset?: integer
302
): ItemList;
303
304
model ItemList {
305
items: Item[];
306
total: integer;
307
hasMore: boolean;
308
}
309
```
310
311
### Header Parameters
312
```typescript
313
@route("/items")
314
@get op listItems(
315
@header("X-API-Version") apiVersion?: string,
316
@query userId?: integer
317
): Item[];
318
```
319
320
### Custom Response Models
321
```typescript
322
@route("/items/{id}")
323
@delete op deleteItem(@path id: integer): DeleteResponse;
324
325
model DeleteResponse {
326
success: boolean;
327
message: string;
328
deletedId: integer;
329
}
330
```
331
332
### Error Responses
333
```typescript
334
model ErrorResponse {
335
error: {
336
code: string;
337
message: string;
338
details?: string[];
339
};
340
}
341
342
@route("/items/{id}")
343
@get op getItem(@path id: integer): Item | ErrorResponse;
344
```
345
346
## Testing Prompts
347
348
After adding operations, test with these prompts:
349
350
**GET Operations:**
351
- "List all items and show them in a table"
352
- "Show me items for user ID 1"
353
- "Get the details of item 42"
354
355
**POST Operations:**
356
- "Create a new item with title 'My Task' for user 1"
357
- "Add an item: title 'New Feature', description 'Add login'"
358
359
**PATCH Operations:**
360
- "Update item 10 with title 'Updated Title'"
361
- "Change the status of item 5 to completed"
362
363
**DELETE Operations:**
364
- "Delete item 99"
365
- "Remove the item with ID 15"
366
367
## Best Practices
368
369
### Parameter Naming
370
- Use descriptive parameter names: `userId` not `uid`
371
- Be consistent across operations
372
- Use optional parameters (`?`) for filters
373
374
### Documentation
375
- Add JSDoc comments to all operations
376
- Describe what each parameter does
377
- Document expected responses
378
379
### Models
380
- Use `@visibility(Lifecycle.Read)` for read-only fields like `id`
381
- Use `@format("date-time")` for date fields
382
- Use union types for enums: `"active" | "completed"`
383
- Make optional fields explicit with `?`
384
385
### Confirmations
386
- Always add confirmations to destructive operations (DELETE, PATCH)
387
- Show key details in confirmation body
388
- Use warning emoji (⚠️) for irreversible actions
389
390
### Adaptive Cards
391
- Keep cards simple and focused
392
- Use conditional rendering with `${if(..., ..., 'N/A')}`
393
- Include action buttons for common next steps
394
- Test data binding with actual API responses
395
396
### Routing
397
- Use RESTful conventions:
398
- `GET /items` - List
399
- `GET /items/{id}` - Get one
400
- `POST /items` - Create
401
- `PATCH /items/{id}` - Update
402
- `DELETE /items/{id}` - Delete
403
- Group related operations in the same namespace
404
- Use nested routes for hierarchical resources
405
406
## Common Issues
407
408
### Issue: Parameter not showing in Copilot
409
**Solution**: Check parameter is properly decorated with `@query`, `@path`, or `@body`
410
411
### Issue: Adaptive card not rendering
412
**Solution**: Verify file path in `@card` decorator and check JSON syntax
413
414
### Issue: Confirmation not appearing
415
**Solution**: Ensure `@capabilities` decorator is properly formatted with confirmation object
416
417
### Issue: Model property not appearing in response
418
**Solution**: Check if property needs `@visibility(Lifecycle.Read)` or remove it if it should be writable
419

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,693 prompts

More by @OpenSourceBuffGuy

See all
Woman in satin bustier taking indoor selfie prompt image

Woman in satin bustier taking indoor selfie

Recreates a reference smartphone selfie as a new adult woman in a luxury living room, matching crop, light and styling while leaving out all on-screen text and icons.

image-prompt, json-prompt, gpt-image, reference-image, selfie, portrait, woman, photorealistic, smartphone-photo, natural-light, fashion, jewelry, hairstyles, interior-design, negative-prompt, structured-output, vertical-format, close-up, social-media-graphic, long-form, advanced

Chest-up editorial portrait in oversized black blazer prompt image

Chest-up editorial portrait in oversized black blazer

Turns a reference photo into a chest-up fashion editorial portrait in an oversized black blazer, with a locked identity and soft side sunlight on a white wall.

image-prompt, gpt-image, reference-image, face-reference, portrait, woman, editorial, fashion, fashion-shoot, medium-shot, natural-light, white-background, vertical-format, photorealistic, luxury, negative-prompt, guardrails, photography, for-photographers, for-artists, quick, bokeh, headshot, soft-lighting

Skater clears a stair set in one low tracking shot prompt image

Skater clears a stair set in one low tracking shot

Writes a 30-second continuous low tracking shot of a skateboarder clearing stairs at golden hour, in six-second beats with a locked face and outfit.

video-prompt, timed-beats, tracking-shot, single-take, camera-movement, action, sports, kling, character-consistency, golden-hour, low-angle, natural-light, wide-shot, photorealistic, cinematic, guardrails, for-filmmakers, man, full-body, slow-motion, structured-output

Reviews

Loading reviews…

Discussion

Loading comments…