GraphQL API for a blog using Strawberry, a modern GraphQL library for Python.

Set Up Your Environment

  1. Install Python: Ensure Python is installed on your system.
  2. Install Strawberry:
    bash
    pip install strawberry

Step 2: Create the GraphQL API

  1. Create a new directory for your project:
    bash
    mkdir strawberry_blog
    cd strawberry_blog
  2. Create a file named main.py:
    bash
    touch main.py

Step 3: Write the GraphQL API

In main.py, write the following code:

python
import strawberry
from typing import List, Optional

# In-memory "database" for blog posts
posts = []

# GraphQL type for a blog post
@strawberry.type
class Post:
    id: int
    title: str
    content: str
    author: str

# GraphQL query type
@strawberry.type
class Query:
    @strawberry.field
    def posts(self) -> List[Post]:
        return posts

    @strawberry.field
    def post(self, post_id: int) -> Optional[Post]:
        for post in posts:
            if post.id == post_id:
                return post
        return None

# GraphQL mutation type
@strawberry.type
class Mutation:
    @strawberry.mutation
    def create_post(self, title: str, content: str, author: str) -> Post:
        post = Post(
            id=len(posts) + 1,
            title=title,
            content=content,
            author=author,
        )
        posts.append(post)
        return post

    @strawberry.mutation
    def update_post(self, post_id: int, title: str, content: str, author: str) -> Optional[Post]:
        for post in posts:
            if post.id == post_id:
                post.title = title
                post.content = content
                post.author = author
                return post
        return None

    @strawberry.mutation
    def delete_post(self, post_id: int) -> bool:
        for post in posts:
            if post.id == post_id:
                posts.remove(post)
                return True
        return False

# Create the schema
schema = strawberry.Schema(query=Query, mutation=Mutation)

Step 4: Run the GraphQL API

Start the Strawberry server using the built-in ASGI server:

bash
strawberry server main

This will start the server at http://127.0.0.1:8000.


Step 5: Test the API

You can test the API using the built-in GraphQL Playground or any GraphQL client like Postman or Insomnia.

  1. GraphQL Playground: Open your browser and go to http://127.0.0.1:8000/graphql. This will display an interactive GraphQL Playground where you can test queries and mutations.
  2. Example Queries and Mutations:
    • Create a Post:
      graphql
      mutation {
        createPost(title: "My First Post", content: "This is my first blog post.", author: "John Doe") {
          id
          title
          content
          author
        }
      }
    • Get All Posts:
      graphql
      query {
        posts {
          id
          title
          content
          author
        }
      }
    • Get a Single Post:
      graphql
      query {
        post(postId: 1) {
          id
          title
          content
          author
        }
      }
    • Update a Post:
      graphql
      mutation {
        updatePost(postId: 1, title: "Updated Post", content: "This post has been updated.", author: "John Doe") {
          id
          title
          content
          author
        }
      }
    • Delete a Post:
      graphql
      mutation {
        deletePost(postId: 1)
      }

Step 6: Example Workflow

  1. Create a Post:
    • Use the createPost mutation to add a new post.
    • Example:
      graphql
      mutation {
        createPost(title: "My First Post", content: "This is my first blog post.", author: "John Doe") {
          id
          title
          content
          author
        }
      }
  2. Get All Posts:
    • Use the posts query to retrieve all posts.
    • Example:
      graphql
      query {
        posts {
          id
          title
          content
          author
        }
      }
  3. Get a Single Post:
    • Use the post query to retrieve a specific post by ID.
    • Example:
      graphql
      query {
        post(postId: 1) {
          id
          title
          content
          author
        }
      }
  4. Update a Post:
    • Use the updatePost mutation to update a post.
    • Example:
      graphql
      mutation {
        updatePost(postId: 1, title: "Updated Post", content: "This post has been updated.", author: "John Doe") {
          id
          title
          content
          author
        }
      }
  5. Delete a Post:
    • Use the deletePost mutation to delete a post.
    • Example:
      graphql
      mutation {
        deletePost(postId: 1)
      }

Step 7: Optional Enhancements

  1. Persistent Storage: Use a database like SQLitePostgreSQL, or MongoDB to store posts instead of an in-memory list.
  2. Authentication: Add user authentication using JWT or OAuth2.
  3. Pagination: Implement pagination for the posts query.
  4. Validation: Add more validation for post data (e.g., minimum title length).
  5. Deployment: Deploy the API to a cloud platform like HerokuAWS, or Google Cloud.