Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added docs for graphql-vs-openAPI #325

Merged
merged 19 commits into from
Aug 2, 2024

Conversation

scshiv29-dev
Copy link
Contributor

@scshiv29-dev scshiv29-dev commented Jul 10, 2024

/claim #323
fixes #323

@scshiv29-dev
Copy link
Contributor Author

@amitksingh1490 could you please review this ?

@amitksingh1490
Copy link
Contributor

Tonality of the article can be improved

  1. Add more conversational elements and rhetorical questions to engage the reader. For example:

"Choosing between GraphQL and OpenAPI? Buckle up, because we're about to dive into the exciting world of API specifications!"

  1. Use more vibrant language and metaphors. For instance:

"Think of GraphQL as a Swiss Army knife for your data needs - it's flexible, precise, and can handle just about any query you throw at it."

  1. Incorporate more personal touches and opinions:

"As someone who's worked with both GraphQL and OpenAPI, I can tell you that each has its sweet spots. Let's explore when to reach for which tool in your API toolkit."

  1. Add some humor or playful elements:

"REST vs. GraphQL debates can get as heated as the tabs vs. spaces argument. But don't worry, we'll navigate these choppy waters together!"

  1. Use more active voice and shorter sentences for a punchier feel:

"GraphQL shines in real-time applications. It handles complex queries with ease. And evolving requirements? GraphQL's got you covered."

  1. Incorporate more real-world analogies:

"If OpenAPI is like a well-organized library with clear sections and a detailed catalog, GraphQL is more like a personal librarian who fetches exactly the books you need - no more, no less."

  1. Add more enthusiasm and exclamation points (but don't overdo it):

"The future of APIs is looking bright! With GraphQL pushing the boundaries of flexibility and OpenAPI continually evolving, we're in for some exciting developments!"

Apply these principles throughout the article.

The article also lacks depth

For example

  1. GraphQL's Query Flexibility:

Original: "GraphQL allows clients to define the structure of the response, making it highly flexible."

Expanded: "GraphQL's query flexibility is a game-changer for frontend developers. Imagine you're building a user profile page that needs to display a user's name, email, recent posts, and follower count. With a REST API, you might need to make multiple requests to different endpoints (/user, /posts, /followers) to gather all this data. But with GraphQL, you can request all this information in a single query:

query {
  user(id: "123") {
    name
    email
    recentPosts(limit: 5) {
      title
      date
    }
    followerCount
  }
}

This not only reduces the number of network requests but also eliminates over-fetching of data. If you only need the user's name and email, you simply omit the other fields from your query. This flexibility allows frontend developers to iterate quickly without waiting for backend changes, significantly speeding up development cycles."

  1. OpenAPI's Schema Validation:

Original: "OpenAPI relies on JSON Schema for defining and validating the structure of API requests and responses, providing robust validation at the design stage."

Expanded: "OpenAPI's use of JSON Schema for validation is more powerful than it might initially appear. Let's break this down with an example. Suppose you're building an e-commerce API. You could define a product schema like this:

components:
  schemas:
    Product:
      type: object
      required:
        - id
        - name
        - price
      properties:
        id:
          type: integer
        name:
          type: string
          minLength: 1
          maxLength: 100
        price:
          type: number
          minimum: 0
        description:
          type: string
        categories:
          type: array
          items:
            type: string

This schema does more than just define the structure. It enforces business rules:

  • Products must have an id, name, and price (required fields)
  • Product names must be between 1 and 100 characters
  • Prices can't be negative

By defining these constraints in the OpenAPI spec, you're not just documenting your API - you're creating a contract that can be enforced by API gateways, automatically validated in tests, and used to generate accurate client SDKs. This level of detail at the design stage catches errors early, improves API consistency, and significantly reduces the likelihood of bugs in production."

  1. GraphQL's Real-Time Capabilities:

Original: "GraphQL's support for subscriptions enables real-time data updates, catering to the growing demand for real-time applications."

Expanded: "GraphQL's subscription feature is a powerful tool for building real-time applications, but it's worth diving into how this actually works and why it's so effective. Unlike queries and mutations, which follow a request-response model, subscriptions establish a steady connection between the client and the server, typically using WebSockets.

Here's a practical example: imagine you're building a live-updating stock trading application. With GraphQL subscriptions, you could set up something like this:

subscription {
  stockPriceUpdate(symbol: "AAPL") {
    price
    change
    lastUpdated
  }
}

Once this subscription is set up, the server will push updates to the client whenever the stock price changes. This is much more efficient than polling an endpoint repeatedly, as it reduces unnecessary network traffic and server load.

The real power comes from combining subscriptions with queries and mutations. For instance, a user could place a buy order (mutation), fetch their current portfolio (query), and receive real-time updates on their stocks (subscription) all through the same GraphQL endpoint. This unified approach to real-time and request-response operations simplifies client-side state management and provides a smoother user experience.

Moreover, GraphQL's type system applies to subscriptions too, ensuring that real-time data adheres to your schema. This consistency across all operations is a significant advantage when building complex, real-time applications."

  1. Performance Considerations:

Original: "GraphQL's ability to fetch specific data reduces response time and bandwidth usage. OpenAPI's predefined endpoints can sometimes lead to over-fetching or under-fetching data."

Expanded: "Let's dive deeper into the performance implications of GraphQL vs OpenAPI.

With GraphQL, the ability to request only needed fields can significantly reduce payload sizes. For example, if you're building a mobile app that displays a list of products, you might only need the product name, price, and thumbnail image. In a REST API, you might get all product details including lengthy descriptions, inventory data, etc. This extra data increases the payload size and parsing time on mobile devices.

Here's a concrete example:

REST API response (over-fetching):

{
  "id": 1,
  "name": "Smartphone X",
  "price": 999.99,
  "description": "A very long description...",
  "inventory": 500,
  "categoryId": 5,
  "brandId": 3,
  "specs": { ... },
  "reviews": [ ... ],
  "relatedProducts": [ ... ]
}

GraphQL query and response (precise data):

query {
  product(id: 1) {
    name
    price
    thumbnailUrl
  }
}
{
  "data": {
    "product": {
      "name": "Smartphone X",
      "price": 999.99,
      "thumbnailUrl": "https://example.com/thumb.jpg"
    }
  }
}

The GraphQL response is much smaller, leading to faster load times, especially on slower networks.

However, it's not all roses for GraphQL. Complex queries can put a heavier load on your database. For instance, a deeply nested query fetching users, their posts, comments on those posts, and information about the comment authors could result in multiple joins or separate database queries. This is where techniques like DataLoader (for batching and caching) become crucial in GraphQL implementations.

On the OpenAPI side, while over-fetching can be an issue, it also allows for easier caching at the network level (CDNs, reverse proxies) because the responses for a given URL are consistent. Additionally, for simple CRUD operations, the RESTful approach can be more straightforward to implement and may perform better out of the box."

  1. Developer Experience:

Original: "GraphQL's flexibility presents a steeper learning curve, supported by vibrant communities and resources. OpenAPI's structured approach is easier for developers familiar with REST, benefiting from long-standing tools and documentation."

Expanded: "The developer experience difference between GraphQL and OpenAPI goes beyond just the initial learning curve. Let's break this down:

GraphQL:

  • Learning Curve: While GraphQL concepts like schemas, resolvers, and the query language itself take time to master, tools like GraphiQL provide an interactive playground that significantly eases the learning process. Developers can explore the API, auto-complete queries, and see instant results.

  • Tooling: The GraphQL ecosystem has evolved rapidly. Tools like Apollo Client not only help with querying but also provide powerful caching mechanisms, state management, and optimistic UI updates. Here's a quick example of how Apollo Client simplifies data fetching in React:

    const GET_USER = gql`
      query GetUser($id: ID!) {
        user(id: $id) {
          name
          email
        }
      }
    `;
    
    function UserProfile({ userId }) {
      const { loading, error, data } = useQuery(GET_USER, {
        variables: { id: userId },
      });
    
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error :(</p>;
    
      return <h1>{data.user.name}</h1>;
    }

    This declarative approach to data fetching can significantly simplify frontend code.

  • Type Safety: GraphQL's strong typing, when combined with tools like TypeScript, can provide end-to-end type safety from your API to your frontend code, catching errors at compile time.

OpenAPI:

  • Familiarity: For developers already versed in REST principles, OpenAPI feels like a natural extension. Its structure mirrors typical REST endpoints, making it easier to adopt in existing projects.

  • Code Generation: One of OpenAPI's strengths is the ability to generate both server and client code. For example, using a tool like Swagger Codegen, you can generate a fully functional API client in multiple languages from your OpenAPI spec. This can dramatically speed up development and reduce inconsistencies between API documentation and implementation.

  • Standardization: OpenAPI's widespread adoption means that many cloud platforms and API gateways natively support OpenAPI specifications. For instance, Azure API Management can import an OpenAPI spec and automatically set up routing, request validation, and even mock responses for testing.

In practice, the choice often comes down to the specific needs of your project and team. GraphQL shines in scenarios with complex, interconnected data and when you need a flexible, powerful query language. OpenAPI excels in scenarios where you need a clear, standards-based approach, especially when working with external partners or in highly regulated environments."

These are some places the article lacks depth Please rework on them marking this as draft

@amitksingh1490 amitksingh1490 marked this pull request as draft July 12, 2024 12:48
@scshiv29-dev
Copy link
Contributor Author

@amitksingh1490 made reviewed changes , some part is still not deep into it as the article was already too long 5600 words.
Let me know if and where I can improve . thanks

@scshiv29-dev scshiv29-dev marked this pull request as ready for review July 13, 2024 03:33
graphql/graphql-vs-openapi.md Outdated Show resolved Hide resolved
@amitksingh1490
Copy link
Contributor

@scshiv29-dev Added detailed comments, this will reduce the word count significantly and will give you space to expand on things which are more important for the context of this blog

@scshiv29-dev
Copy link
Contributor Author

@amitksingh1490 made some changes, resolved conversations where I thought the change satisfies the review, others I've added comments and left open . Please review this and let me know if I could do better. Thanks .

.gitpod.yml Outdated Show resolved Hide resolved
@amitksingh1490
Copy link
Contributor

@scshiv29-dev moving this to draft as there are lot of factually incorrect claims, please do some research on those items and address the comments

@amitksingh1490 amitksingh1490 marked this pull request as draft July 18, 2024 05:29
@Frenzyritz13
Copy link
Contributor

Hey @amitksingh1490, this article is good for the most part, but it is very long; I would recommend splitting it into 3 parts. Let me know if you would like me to take a call there, We will only need two short introductions for the later two parts we split it into.

@amitksingh1490
Copy link
Contributor

sure @Frenzyritz13 go ahead

@scshiv29-dev scshiv29-dev marked this pull request as ready for review July 18, 2024 11:12
@scshiv29-dev scshiv29-dev marked this pull request as draft July 18, 2024 11:19
@scshiv29-dev
Copy link
Contributor Author

@amitksingh1490 I made the reviewed changes . @Frenzyritz13 let me know how you would like me to split this into 3 parts even I think its too big .

@scshiv29-dev scshiv29-dev marked this pull request as ready for review July 18, 2024 11:52
@Frenzyritz13
Copy link
Contributor

Hey @scshiv29-dev you can go through this checklist and tell me if you need more help splitting up the article: https://docs.google.com/document/d/1Bw9iT4ws9q093kCJsnStfpByJljn-wRPNtc575s3_R8/edit?usp=sharing
Here's my calendly link if you want to hop on a call and discuss it further: https://calendly.com/ritvi

@scshiv29-dev
Copy link
Contributor Author

@Frenzyritz13 I've scheduled a call with you at 2:00pm - 2:30pm on Aug 1st to discuss this.

@scshiv29-dev
Copy link
Contributor Author

@amitksingh1490 @Frenzyritz13 I've converted the blog into a 3 part series, please review it and let me know if something needs changing. Thanks

@amitksingh1490 amitksingh1490 enabled auto-merge (squash) August 2, 2024 10:15
@amitksingh1490 amitksingh1490 merged commit 33534f0 into tailcallhq:develop Aug 2, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

doc: Write a Guide Comparing GraphQL vs OpenAPI
3 participants