GraphQL: Building Flexible APIs for Modern Apps

GraphQL is a query language for APIs. It lets clients request exactly the data they need, reducing over-fetching and under-fetching.

## Why GraphQL?

- Fetch only needed data in a single request
- Strongly typed schema
- Real-time with subscriptions
- Great developer tools (GraphiQL)
- Self-documenting

## Schema Definition

```graphql
type User {
 id: ID!
 name: String!
 email: String!
 posts: [Post!]!
}

type Post {
 id: ID!
 title: String!
 content: String!
 author: User!
}

type Query {
 user(id: ID!): User
 posts: [Post!]!
}

type Mutation {
 createPost(title: String!, content: String!): Post!
}
```

## Querying

```graphql
query {
 user(id: "1") {
   name
   posts {
     title
   }
 }
}
```

## Mutations

```graphql
mutation {
 createPost(title: "Hello", content: "World") {
   id
   title
 }
}
```

## Server Setup (Node.js)

```javascript
const { ApolloServer } = require('@apollo/server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
```

## Conclusion

GraphQL simplifies API development for complex frontends. Start small with a few queries and grow your schema organically.

评论
暂无评论