DEV Community

Cover image for Versioning GraphQL and Rest API's
guigoncalves
guigoncalves

Posted on • Originally published at dev.to

Versioning GraphQL and Rest API's

When building an API, it's important to consider how you will handle versioning. The ability to evolve your API over time while maintaining backwards compatibility is crucial for ensuring a smooth experience for your users. In this article, we'll go over some best practices for versioning a GraphQL API and a REST API, and how to implement them with code snippets.

Handling versioning with version on header:
One common approach to versioning API is to use a field or header to specify the version. This allows clients to specify which version of the API they want to use, and the server can respond accordingly. For example, a client could include a version field in their query, and the server would use that to determine which schema/resource to use.

GraphQL example:

const express = require("express");
const graphqlHTTP = require("express-graphql");

const app = express();

const schemaV1 = /* your v1 schema */;
const schemaV2 = /* your v2 schema */;

app.use("/graphql", graphqlHTTP((req) => {
    const version = req.headers["version"];
    const schema = version === "v1" ? schemaV1 : schemaV2;
    return {
        schema,
        graphiql: true
    };
}));
Enter fullscreen mode Exit fullscreen mode

In this example, the server is using the version header passed in by the client to determine which schema to use.

Handling versioning with url:
A common approach to versioning REST API's is to include the version number in the URL. For example, you could have /v1/resource and /v2/resource as your endpoint for different versions of your API.

const express = require("express");
const app = express();

app.use("/v1/resource", (req, res) => {
    // v1 resource endpoint
});

app.use("/v2/resource", (req, res) => {
    // v2 resource endpoint
});
Enter fullscreen mode Exit fullscreen mode

In this example, the server is using different endpoint for different versions of your API.

Best practices:

  • Avoid making breaking changes to the API
  • Introduce new fields or types, or deprecate old fields or types in GraphQL API
  • Introduce new endpoints or deprecate old endpoints in REST API
  • Provide a migration path for existing clients
  • Document the API clearly and communicate changes to users
  • Provide release notes and detailed documentation for each field, type or endpoint.

Top comments (0)