# GraphQL Basics ## What is GraphQL? GraphQL is a query language for APIs that allows clients to request exactly the data they need. ## Core Concepts ### Schema & Types ```graphql type User { id: ID! name: String! email: String age: Int posts: [Post!]! createdAt: DateTime! } type Post { id: ID! title: String! content: String author: User! comments: [Comment!]! } type Query { user(id: ID!): User users(limit: Int = 10): [User!]! post(id: ID!): Post } type Mutation { createUser(name: String!, email: String!): User! updateUser(id: ID!, name: String): User! deleteUser(id: ID!): Boolean! } type Subscription { userCreated: User! postUpdated(id: ID!): Post! } ``` ### Queries ```graphql # Fetch single user query GetUser($id: ID!) { user(id: $id) { name email posts { title } } } # Fetch multiple users with filtering query GetUsers($limit: Int) { users(limit: $limit) { id name email } } ``` ### Mutations ```graphql mutation CreateUser($name: String!, $email: String!) { createUser(name: $name, email: $email) { id name } } mutation UpdatePost($id: ID!, $title: String!) { updatePost(id: $id, title: $title) { id title updatedAt } } ``` ### Variables ```json { "id": "123", "name": "John", "email": "john@example.com" } ``` ## Implementation (Node.js + Apollo) ### Basic Server ```javascript const { ApolloServer, gql } = require('apollo-server'); const { GraphQLScalarType, Kind } = require('graphql'); const typeDefs = gql` scalar DateTime type User { id: ID! name: String! email: String! createdAt: DateTime! } type Query { users: [User!]! user(id: ID!): User } type Mutation { createUser(name: String!, email: String!): User! } type Subscription { userCreated: User! } `; const resolvers = { DateTime: new GraphQLScalarType({ name: 'DateTime', serialize(value) { return value.toISOString(); }, parseValue(value) { return new Date(value); } }), Query: { users: () => users, user: (_, { id }) => users.find(u => u.id === id), }, Mutation: { createUser: (_, { name, email }) => { const newUser = { id: String(users.length + 1), name, email, createdAt: new Date() }; users.push(newUser); return newUser; } } }; const server = new ApolloServer({ typeDefs, effectors }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); }); ``` ### Client (React) ```javascript import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000/graphql', cache: new InMemoryCache() }); const GET_USERS = gql` query GetUsers { users { id name email } } `; function App() { const { loading, error, data } = useQuery(GET_USERS); if (loading) return

Loading...

; if (error) return

Error: {error.message}

; return (
{data.users.map(user => (
{user.name}
))}
); } ``` ## GraphQL vs REST | Feature | GraphQL | REST | |---------|---------|------| | Data fetching | Single request | Multiple endpoints | | Over-fetching | No | Yes | | Under-fetching | No | Sometimes | | Type safety | Yes (schema) | No | | Learning curve | Higher | Lower | | Caching | Manual | Automatic | | File uploads | Complex | Simple | ## Best Practices 1. **N+1 Problem** - Use DataLoader for batching 2. **Pagination** - Use cursor-based pagination 3. **Error Handling** - Return meaningful errors 4. **Security** - Implement depth limiting 5. **Performance** - Consider query cost analysis