API Connect

API Connect

Join this online group to communicate across IBM product users and experts by sharing advice and best practices with peers and staying up to date regarding product enhancements.


#API Connect
#Applicationintegration
#APIConnect
 View Only

Building GraphQL APIs using IBM API Connect for GraphQL

By Timil Titus posted 27 days ago

  

In today's data-driven world, organizations often struggle with data fragmentation across multiple sources. Modern applications need to access data from REST APIs, databases, and other services, leading to complex integration challenges. GraphQL has emerged as a powerful solution for these problems, offering a unified query language for your API needs.

This blog post explores how to leverage IBM APIConnect for Graphql to build a unified GraphQL API that seamlessly combines data from different sources. We'll demonstrate a practical approach using the powerful @materializer directive to connect REST APIs with database queries.

What is IBM API Connect for GraphQL?

IBM API Connect for GraphQL as a Service is a modern API platform that lets you build GraphQL APIs and MCP Servers for all your data sources using a declarative approach. APIs run in an in-memory Golang based GraphQL engine deployed into Kubernetes, and are highly responsive to application needs. Delivered as a fully managed SaaS, it enables developers to create concise, performant GraphQL APIs and agent ready MCP servers in minutes, deploy in seconds, and run securely without managing infrastructure.

APIs are built using a declarative approach, allowing developers to compose GraphQL schemas, federated graphs (supergraphs), and MCP endpoints by combining building blocks that describe your enterprise data. Strong introspection and schema composition mean you can model and expose your data; for applications, agents, or AI; with just a few lines of code.

The platform runs on a high-performance, in memory Golang based engine deployed to Kubernetes, delivering low latency, high throughput, and minimal backend load. At runtime, it optimizes queries and orchestrates access to your backends, whether they are public or private, SQL, NoSQL, REST, SOAP/XML, or even other GraphQL APIs.

Prerequisites

Before we begin, you'll need an environment in IBM API Connect for GraphQL (IBM API Connect for GraphQL)

Getting Started

Setting Up Your Environment

First, install the stepzen CLI:

npm install -g stepzen@latest

Then, log in to your IBM API Connect for GraphQL environment using your IBM environment:

stepzen login <domain> -i <instance_id>

Create a GraphQL API in minutes by combining the data multiple datasources

One of IBM API Connect for GraphQL's most powerful features is the @materializer directive, which allows you to connect different GraphQL subgraphs. This enables you to build a "graph of graphs" - a unified API that combines data from multiple sources.

In our example, we'll build a unified API that combines:

  1. Customer data from a REST API
  2. Order data from a MySQL database

Step 1: Creating a GraphQL API for REST Data

Let's start by creating a GraphQL API that connects to a REST endpoint for customer data.

Create a new folder for your project:

mkdir gql-demo
cd gql-demo

Import the customers REST API using IBM API Connect for GraphQL's import feature:

stepzen import curl https://introspection.apis.stepzen.com/customers --query-name "customers" --query-type "Customer" --name "customers"

This command introspects the REST API and generates a GraphQL schema. Now, let's deploy this schema:

stepzen deploy

You can now test your GraphQL API using the GraphiQL interface. Try running below query against the deployed endpoint:

query CustomerQuery {
    customers {
        email
        id
        name
        address {
            city
            countryRegion
            id
            postalCode
            stateProvince
            street
        }
    }
}

For our use case, we want to focus only on customer data. Let's update the schema to include just what we need:

type Address {
    city: String
    countryRegion: String
    id: Int
    postalCode: String
    stateProvince: String
    street: String
}   

type CustomerEntry {
    address: Address
    email: String
    id: Int
    name: String
}

type Query {
    customers: [CustomerEntry]
        @rest(endpoint: "https://introspection.apis.stepzen.com/customers")
}

Step 2: Creating a GraphQL API for MySQL Data

Next, let's create a GraphQL API for order data stored in a MySQL database:

stepzen import mysql://<db-host>:<port>/<database>

Update the generated schema to focus only on order data:

type Order {
    carrier: String!
    createdAt: Date!
    id: Int!
    shippingCost: Float
    trackingId: String!
    customerId: Int!
}

type Query {
    ordersForACustomer(customerId: Int!): [Order]
        @dbquery(type: "mysql", table: "order", configuration: "mysql_config")
}

Now, let's deploy this schema:

stepzen deploy

Try running below query against the deployed endpoint:

query OrdersForACustomer {
    ordersForACustomer(customerId: 1) {
        carrier
        createdAt
        customerId
        id
        shippingCost
        trackingId
    }
}

Step 3: Combining Subgraphs with @materializer directive

Now comes the magic! We'll use the @materializer directive to connect our customer data with order data. Create a new file called customer-orders.graphql:

extend type CustomerEntry {
    orders: [Order]
        @materializer(
            query: "ordersForACustomer"
            arguments: [{name: "customerId", field: "id"}]
        )
}

This directive tells IBM API Connect for GraphQL to:

  1. Extend the CustomerEntry type with an orders field
  2. Populate this field by calling the ordersForACustomer query
  3. Pass the customer's id as the customerId argument

Finally, update your index.graphql file to include all schemas:

schema @sdl(files: ["customers/index.graphql", "mysql/index.graphql", "customer-orders.graphql"]) {
    query: Query
}

Deploy your endpoint using stepzen deploy and test the unified API:

query CustomerOrders {
    customers {
        id
        email
        name
        orders {
            carrier
            createdAt
            customerId
            shippingCost
            id
        }
    }
}

Benefits

By using IBM API Connect for GraphQL with the @materializer directive, we've achieved several benefits:

  1. Unified API: Clients can access both customer and order data through a single GraphQL endpoint.
  2. Declarative Approach: No custom code needed to join data - just declarative schema definitions.
  3. Optimized Performance: IBM API Connect for GraphQL handles the execution of queries efficiently.
  4. Scalability: Easy to add more data sources as your application grows.

Conclusion

IBM API Connect for GraphQL's @materializer directive provides a powerful way to build unified GraphQL APIs that combine data from multiple sources. By following the steps outlined in this blog post, you can create a seamless API experience for your applications, regardless of where your data resides.

IBM API Connect for GraphQL offers a robust platform for building, deploying, and managing GraphQL APIs. This approach significantly reduces the complexity of data integration while providing a flexible and scalable solution for your API needs.

Next Steps

  • Explore more advanced features of IBM API Connect for GraphQL, such as caching and custom resolvers
  • Add authentication and authorization to your GraphQL API
  • Integrate additional data sources, such as other databases or third-party APIs

For more details, please visit https://www.ibm.com/docs/en/api-connect-graphql/saas

Happy coding!

1 comment
11 views

Permalink

Comments

13 days ago

Impressive walkthrough! The @materializer directive truly simplifies complex data integration, empowering developers to build unified, high-performance GraphQL APIs with ease using IBM API Connect for GraphQL. Exciting innovation ahead!