AI
50 AI Prompts for GraphQL and Apollo Server Development
50 AI prompts for building GraphQL APIs with Apollo Server and Node.js. Covers schema design, resolvers, mutations, subscriptions, DataLoader, authentication, caching, federation, and testing.
Getting the Most from These GraphQL Prompts
GraphQL shifts API design from endpoints to a type system. The schema defines everything the client can query; resolvers implement it. This structure means a lot of the work in GraphQL is design work — choosing types, defining relationships, deciding what belongs in a query versus a mutation. These prompts help with both the design decisions and the implementation boilerplate.
All prompts assume Apollo Server 4, Node.js 20, and TypeScript with code-first schema generation using TypeGraphQL, or schema-first with a .graphql file and graphql-codegen for types. Specify which approach your project uses when running any schema-related prompt. The DataLoader and authentication patterns are framework-agnostic and work with any GraphQL server.
Schema Design and Resolvers (Prompts 1-16)
Prompt 1: Design a GraphQL schema for a blogging platform. Define types for User (id, email, displayName, avatarUrl, posts, followers, following), Post (id, title, slug, body, publishedAt, author, tags, comments, likeCount), Comment (id, body, author, post, createdAt), and Tag (id, name, slug, posts). Use connections for paginated lists. Include all necessary input types for mutations and show how to represent the follower/following relation without circular type definitions.
Prompt 2: Write Apollo Server 4 resolver functions for a User type. Implement the id, email, and displayName fields as trivial resolvers, the avatarUrl field with a CDN URL transformation, the posts field with cursor-based pagination, and the followers field that defers to a DataLoader to avoid N+1 queries. Show the resolver map structure and TypeScript types. Prompt 3: Create a GraphQL mutation for creating a blog post. Define the CreatePostInput type with title, body, and tagIds. Write the resolver that validates the input with class-validator, creates the post in the database, associates the tags, publishes a PostCreated event to a message bus, and returns the created post. Show the error handling for duplicate slugs returning a UserError type instead of throwing.
- Prompt 4: Write a GraphQL subscription for real-time comment notifications. Use Apollo Server subscriptions with graphql-subscriptions PubSub, publish a CommentAdded event from the createComment mutation resolver, filter subscription events by postId so clients only receive comments for the post they are viewing, and show the WebSocket transport setup in Apollo Server 4.
- Prompt 5: Create a GraphQL union type for a search result that can return a User, Post, or Tag. Write the resolver that queries all three models in parallel, merges and sorts results by relevance score, and returns them as a union. Show how to write the __resolveType function and how to query the union on the client with inline fragments.
- Prompt 6: Write a GraphQL interface for a Node type that all primary entities implement. Add an id field of type ID. Show how User, Post, and Comment implement the Node interface, write a node query that fetches any entity by its global ID, encode global IDs as base64 of TypeName:dbId, and decode them in the node resolver.
- Prompt 7: Create a GraphQL enum type for PostStatus (DRAFT, PUBLISHED, ARCHIVED) and integrate it into the Post schema. Write a resolver for changing post status that validates allowed transitions (DRAFT to PUBLISHED is allowed, PUBLISHED to DRAFT is not), and return a structured error when the transition is invalid.
- Prompt 8: Write custom GraphQL scalar types for Date (ISO 8601 string), URL (validates format), Email (validates format), and JSON (arbitrary JSON object). Show the scalar implementations with parseValue, parseLiteral, and serialize, and add them to the Apollo Server schema.
- Prompt 9: Create a GraphQL schema for a multi-tenant SaaS application. Every query and mutation should be scoped to the authenticated user organisation. Show how to add an organisationId to the resolver context, write a middleware that injects it from the JWT, and create a base query type that automatically scopes database queries to the current organisation without repeating the filter in every resolver.
- Prompt 10: Write a GraphQL DataLoader setup that batches database calls for a User resolver. The postsLoader batches post IDs and fetches them in one query, the commentsLoader batches comment IDs per post, and the tagsLoader fetches tags for multiple posts in one query. Show how to create loaders per request in the Apollo context factory to avoid cross-request data leaks.
- Prompt 11: Create a GraphQL cursor-based pagination implementation following the Relay specification. Define a Connection type with edges and pageInfo, a cursor that encodes the database row ID as base64, implement first, after, last, and before arguments, and show a resolver for a posts connection that handles all four cases correctly.
- Prompt 12: Write a GraphQL field-level error handling pattern using a union return type. Instead of throwing errors, return a union of Success (the result) or Error (a type with a message and code). Show the schema definition, the resolver that returns one or the other, and how the client handles both cases with inline fragments.
- Prompt 13: Create a GraphQL resolver for a file upload mutation using Apollo Server and graphql-upload. Accept a single file, validate the MIME type and size, store it to S3, and return the public URL. Show the schema definition with the Upload scalar and the multipart form handling setup in Apollo Server 4.
- Prompt 14: Write a GraphQL nested mutation that creates a post with embedded comment creation in a single operation. Use a database transaction so either both succeed or both roll back. Return the created post with the embedded comment in the response.
- Prompt 15: Create a GraphQL schema directive called @deprecated that adds the reason to the field definition and logs a warning when the deprecated field is queried in production. Show the directive implementation, how to apply it in the schema, and how to set up a GraphQL inspector rule that fails CI when deprecated fields are queried.
- Prompt 16: Write a GraphQL persisted queries setup using Apollo Server and a Redis store. The client sends a query hash instead of the full query string, the server looks up the hash in Redis, falls back to the full query on cache miss, stores new queries automatically, and rejects arbitrary queries in production to prevent introspection and query injection attacks.
Authentication, Caching, Federation, and Testing (Prompts 17-50)
Prompt 17: Write a JWT authentication setup for Apollo Server 4. Extract the token from the Authorization header in the context factory, verify it with jsonwebtoken, attach the decoded user to the context, handle expired tokens with a specific error code, and write an @auth schema directive that protects fields or types based on the user role.
Prompt 18: Create an Apollo Server response caching setup using @apollo/server-plugin-response-cache with a Redis store. Cache the allPosts query for 60 seconds, scope the authenticated user feed query per user so caches are not shared, invalidate all post-related cache entries when a post is created or updated, and add a Cache-Control header to the HTTP response. Prompt 19: Write an Apollo Federation setup with two subgraphs: a Users subgraph and a Posts subgraph. The Posts subgraph references User as an external type with the @key directive on userId. Show the Users subgraph __resolveReference implementation, the gateway configuration, and how a client query for posts with their author fields is automatically joined by the gateway.
- Prompt 20: Create a GraphQL rate limiting plugin for Apollo Server that limits query complexity to 100 points per request, calculates complexity by counting fields and multiplying list fields by their limit argument, rejects over-limit queries before execution, and logs the complexity of every query for tuning.
- Prompt 21: Write a GraphQL query depth limiting middleware that rejects queries nested deeper than 7 levels. Show the implementation using graphql-depth-limit, how to configure the maximum depth, and how to add exceptions for specific operations like introspection queries.
- Prompt 22: Create a GraphQL audit logging plugin for Apollo Server that logs every mutation with the operation name, variables (sensitive fields redacted), userId from context, and execution time. Store logs to a database and expose them through an admin-only auditLogs query.
- Prompt 23: Write a Jest unit test for a GraphQL resolver. Mock the database repository, test that the createPost mutation calls the repository with the correct arguments, test that it returns the correct response shape, test that it throws a UserInputError when the title is empty, and test that it publishes a PostCreated event.
- Prompt 24: Create an integration test for a GraphQL API using Apollo Server testClient. Execute real queries against an in-memory test server, seed the database with test data using factories, test the full create-read-update-delete flow for a Post, and verify that authenticated queries reject unauthenticated requests.
- Prompt 25: Write a graphql-codegen configuration that generates TypeScript types from a GraphQL schema file, generates typed hooks for each query and mutation using the Apollo Client plugin, watches for schema changes in development, and outputs types to a src/generated folder that is excluded from git.
FAQ
When should I use GraphQL instead of REST?
GraphQL is the better choice when clients have diverse data requirements — a mobile app needs minimal fields, a dashboard needs many fields, and a third-party needs different fields again. REST requires separate endpoints or over-fetching for these cases. GraphQL is also stronger when your data has complex relationships that clients need to traverse in a single request. See the REST vs GraphQL comparison post on this blog for a full decision framework.
Is Apollo Server the best GraphQL server for Node.js?
Apollo Server 4 is the most widely used and best-documented GraphQL server for Node.js. Alternatives worth considering are GraphQL Yoga (from The Guild), which has excellent plugin support and works well with the Pothos schema builder, and Mercurius for Fastify if performance is a priority. All three handle the core use cases well; Apollo has the largest ecosystem.
How do I prevent N+1 query problems in GraphQL?
Use DataLoader (Prompt 10). DataLoader batches all calls to a resolver that happen within a single event loop tick into one database query. Without it, fetching 20 posts each with their author triggers 21 database queries (1 for posts + 20 for authors). With DataLoader, it triggers 2 queries (1 for posts, 1 for all 20 authors in one batch). DataLoader should be created per request in the Apollo context factory.
Should I use code-first or schema-first GraphQL?
Schema-first (writing a .graphql SDL file) keeps the schema readable and shareable and works well with graphql-codegen for type generation. Code-first (TypeGraphQL, Pothos) keeps everything in TypeScript and avoids schema drift between the SDL and resolvers. Code-first is easier to maintain in large projects where the schema evolves frequently. Schema-first is better for teams where non-developers review or contribute to the API contract.
Related free tools
If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.
Continue Reading
Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.
Free newsletter
Get new guides in your inbox
We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.
No spam. Unsubscribe any time.
Was this article helpful?
Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.