i18n/de/skills/use-graphql-api/SKILL.md
GraphQL-APIs über die Kommandozeile und in TypeScript-Anwendungen abfragen und Mutations durchführen. Behandelt Introspection, Query-Komposition, Variablen, Authentifizierung und Fehlerbehandlung. Verwenden, wenn eine GraphQL-API integriert, eine bestehende REST-Integration migriert oder GraphQL-Operationen debuggt werden sollen.
npx skillsauth add pjt222/agent-almanac use-graphql-apiInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
GraphQL-APIs abfragen und Mutations durchführen, sowohl über die Kommandozeile als auch in TypeScript-Anwendungen.
https://api.example.com/graphql)Das Schema der GraphQL-API entdecken, ohne Dokumentation.
# Einfache Introspection-Query mit curl
curl -s -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ __schema { types { name kind } } }"}' \
| jq '.data.__schema.types[] | select(.kind == "OBJECT") | .name'
# Mit Authentifizierung
curl -s -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{"query": "{ __schema { queryType { fields { name description } } } }"}' \
| jq '.data.__schema.queryType.fields[]'
Für eine vollständigere Schema-Erkundung:
# Vollständige Introspection-Query speichern
cat > /tmp/introspection.json << 'EOF'
{
"query": "{ __schema { types { name kind fields { name type { name kind ofType { name kind } } } } } }"
}
EOF
curl -s -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d @/tmp/introspection.json | jq '.' > /tmp/schema.json
Erwartet: Schema-Typen und verfügbare Query-Felder werden aufgelistet.
Bei Fehler: Wenn Introspection disabled ist (häufig in Produktions-APIs), die offizielle Dokumentation konsultieren oder den API-Anbieter für ein Schema-Dokument kontaktieren.
Queries manuell testen, bevor Code geschrieben wird.
# Einfache Query
curl -s -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{
"query": "query GetUser($id: ID!) { user(id: $id) { id name email } }",
"variables": {"id": "123"}
}' | jq '.'
# Query mit verschachtelten Feldern
curl -s -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{
"query": "{ users(first: 10) { edges { node { id name posts { title } } } pageInfo { hasNextPage endCursor } } }"
}' | jq '.data.users.edges[].node'
Erwartet: JSON-Antwort mit data-Schlüssel, der die angeforderten Felder enthält. Keine errors-Schlüssel.
Bei Fehler: Wenn errors erscheint, den Meldungstext prüfen. Häufige Ursachen: falsche Feldnamen (Schema-Introspection auf korrekte Namen prüfen), fehlende erforderliche Variablen, Berechtigungsfehler.
Eine typisierte GraphQL-Client-Integration in TypeScript einrichten.
# Option 1: Nativer Fetch (kein Client erforderlich)
# Keine Installation nötig
# Option 2: graphql-request (leichtgewichtig)
npm install graphql-request graphql
# Option 3: urql (React-fokussiert)
npm install urql graphql
# Option 4: Apollo Client (vollständig)
npm install @apollo/client graphql
Typisierter Client mit graphql-request:
// src/lib/graphql-client.ts
import { GraphQLClient, gql } from 'graphql-request'
const endpoint = process.env.NEXT_PUBLIC_GRAPHQL_URL!
export const client = new GraphQLClient(endpoint, {
headers: {
authorization: `Bearer ${process.env.API_TOKEN}`,
},
})
// Typen definieren
interface User {
id: string
name: string
email: string
}
interface GetUserQuery {
user: User
}
interface GetUserVariables {
id: string
}
// Typisierte Query-Funktion
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`
export async function getUser(id: string): Promise<User> {
const data = await client.request<GetUserQuery, GetUserVariables>(
GET_USER,
{ id }
)
return data.user
}
Erwartet: Client initialisiert ohne Fehler. getUser()-Funktion gibt typisierte User-Daten zurück.
Bei Fehler: Wenn TypeScript Typfehler meldet, sicherstellen, dass GraphQL-Response-Typen mit den tatsächlichen Schema-Feldern übereinstimmen.
Daten-schreibende Operationen implementieren.
// src/lib/mutations.ts
import { client, gql } from './graphql-client'
interface CreatePostInput {
title: string
content: string
authorId: string
}
interface Post {
id: string
title: string
content: string
createdAt: string
}
interface CreatePostMutation {
createPost: Post
}
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
content
createdAt
}
}
`
export async function createPost(input: CreatePostInput): Promise<Post> {
const data = await client.request<CreatePostMutation>(CREATE_POST, {
input,
})
return data.createPost
}
# Mutation mit curl testen
curl -s -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"query": "mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id title } }",
"variables": {"input": {"title": "Test Post", "content": "Hello", "authorId": "123"}}
}' | jq '.'
Erwartet: Mutation gibt das erstellte Objekt mit ID zurück.
Bei Fehler: Wenn Mutation schlägt mit "Not authorized" fehl, sicherstellen, dass das Auth-Token korrekt formatiert ist (Bearer-Präfix, gültiger Token).
Robuste Fehlerbehandlung für GraphQL-Antworten.
// src/lib/graphql-client.ts (erweitert)
import { ClientError } from 'graphql-request'
export interface GraphQLError {
message: string
locations?: Array<{ line: number; column: number }>
path?: string[]
extensions?: Record<string, unknown>
}
export class GraphQLRequestError extends Error {
constructor(
message: string,
public readonly errors: GraphQLError[],
public readonly status: number
) {
super(message)
this.name = 'GraphQLRequestError'
}
}
export async function safeRequest<T>(
query: string,
variables?: Record<string, unknown>
): Promise<T> {
try {
return await client.request<T>(query, variables)
} catch (error) {
if (error instanceof ClientError) {
const graphqlErrors = error.response.errors ?? []
throw new GraphQLRequestError(
graphqlErrors[0]?.message ?? 'GraphQL request failed',
graphqlErrors,
error.response.status
)
}
throw error
}
}
Erwartet: safeRequest() gibt typisierte Daten zurück oder wirft GraphQLRequestError mit strukturierten Fehlerinformationen.
Bei Fehler: Wenn Fehler-Typen nicht übereinstimmen, GraphQL-Error-Response-Struktur durch Logging von error.response aus ClientError überprüfen.
GraphQL-Queries in Next.js Server-Komponenten oder API-Routen verwenden.
// src/app/users/[id]/page.tsx (Server Component)
import { getUser } from '@/lib/graphql-client'
interface Props {
params: { id: string }
}
export default async function UserPage({ params }: Props) {
const user = await getUser(params.id)
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
)
}
// src/app/api/posts/route.ts (API Route)
import { NextRequest, NextResponse } from 'next/server'
import { createPost } from '@/lib/mutations'
export async function POST(request: NextRequest) {
const body = await request.json()
const post = await createPost({
title: body.title,
content: body.content,
authorId: body.authorId,
})
return NextResponse.json(post)
}
Erwartet: Server-Komponente rendert User-Daten. API-Route erstellt Post und gibt JSON zurück.
Bei Fehler: Wenn Daten nicht auf der Client-Seite erscheinen, sicherstellen, dass die Komponente als Server-Komponente deklariert ist (keine 'use client'-Direktive) und die GraphQL-Antwort korrekt gemappt wird.
errors-Array im Response-Body, nicht im HTTP-Status.DataLoader oder Batching auf API-Seite verwenden.edges/node/pageInfo) statt Offset-Pagination. endCursor korrekt für die nächste Seite weitergeben."123" vs 123 (String vs Int) führt zu Validierungsfehlern.scaffold-nextjs-app — Next.js-App für GraphQL-Integration vorbereitendeploy-to-vercel — GraphQL-integrierte App deployentesting
Launch all available agents in parallel waves for open-ended hypothesis generation on problems where the correct domain is unknown. Use when facing a cross-domain problem with no clear starting point, when single-agent approaches have stalled, or when diverse perspectives are more valuable than deep expertise. Produces a ranked hypothesis set with convergence analysis and adversarial refinement.
tools
Write integration tests for a Node.js CLI application using the built-in node:test module. Covers the exec helper pattern, output assertions, filesystem state verification, cleanup hooks, JSON output parsing, error case testing, and state restoration after destructive tests. Use when adding tests to an existing CLI, testing a new command, verifying adapter behavior across frameworks, or setting up CI for a CLI tool.
development
Screen a proposed trademark for conflicts and distinctiveness before filing. Covers trademark database searches (TMview, WIPO Global Brand Database, USPTO TESS), distinctiveness analysis using the Abercrombie spectrum, likelihood of confusion assessment using DuPont factors and EUIPO relative grounds, common law rights evaluation, and goods/services overlap analysis. Produces a conflict report with a risk matrix. Use before adopting a new brand name, logo, or slogan — distinct from patent prior art search, which uses different databases, legal frameworks, and analysis methods.
tools
Scaffold a new CLI command using Commander.js with options, action handler, three output modes (human-readable, quiet, JSON), and optional ceremony variant. Covers command naming, option design, shared context patterns, error handling, and integration testing. Use when adding a command to an existing Commander.js CLI, designing a new CLI tool from scratch, or standardizing command structure across a multi-command CLI.