Consuming GraphQL API in SAPUI5
Introduction:
GraphQL is a query language for APIs that enables clients to request exactly the data they need. GraphQL is gaining popularity for its flexibility in data fetching. Unlike REST APIs, where multiple endpoints are needed, GraphQL allows clients to fetch only the data they require using a single query. In this blog, we’ll walk through integrating a GraphQL API into a SAPUI5 application using Apollo Client.
Key Features of GraphQL:
- Single Endpoint: All data queries are sent to a single endpoint, simplifying API management.
- Client-Specified Queries: Clients define the structure of the response, ensuring they receive only the necessary data.
- Strongly Typed Schema: APIs are defined by a schema, enabling better validation and introspection.
Comparing OData and GraphQL:
In API query languages, GraphQL and OData stand out as powerful tools that facilitate data retrieval and manipulation. While both serve similar purposes, they exhibit distinct characteristics that cater to different use cases and development paradigms. Here we are discussing the key differences and similarities between GraphQL and OData, supported by examples to illustrate their unique features.
Similarities:
- Query Language for APIs: Both GraphQL and OData serve as query languages for APIs, enabling clients to request specific data from a server.
- Flexibility: Both allow clients to specify exactly which fields they want to retrieve, reducing over-fetching of data and improving performance.
- Hierarchical Structure: Both follow a hierarchical structure, making it easy to navigate and request related data.
Differences:
Schema Definition:
GraphQL requires the explicit definition of a schema, which outlines the types of data that can be queried.
type User {
id: ID!
name: String!
email: String!
}
type Query {
user(id: ID!): User
}
OData uses the Entity Data Model (EDM) to define the data model, including entities and relationships.
<EntityType Name=”User”><Key> <PropertyRef Name=”Id” /></Key><Property Name=”Id” Type=”Edm.Int32″ Nullable=”false” /><Property Name=”Name” Type=”Edm.String” /><Property Name=”Email” Type=”Edm.String” /></EntityType>
Query Language:
GraphQL uses a specific query language that allows clients to request exactly what they need.
query {user(id: “1”) { name email}}
OData relies on URL conventions for querying data.
GET /Users(1)?$select=Name,Email
Complex Queries:
GraphQL excels at handling complex queries, allowing clients to traverse deeply nested data structures.
query {user(id: “1”) { name posts { title comments { text } }}}
OData supports complex queries, but it may require more verbose URLs.
GET /Users(1)?$expand=Posts($expand=Comments($select=Text)),Name,Email
Metadata:
- GraphQL does not have built-in metadata endpoints
- OData exposes metadata, allowing clients to dynamically discover the structure of the API.
· GET /$metadata
Batch Operations:
GraphQL does not have built-in support for batch operations.
OData supports batch requests, allowing multiple operations to be grouped into a single HTTP request.
When to Use GraphQL:
- Complex Data Relationships: Use GraphQL when dealing with complex relationships between data entities, as it allows for efficient traversal of nested data structures.
- Frontend-Driven Development: GraphQL is an excellent choice when the frontend team has a strong influence on data requirements, as it enables them to request exactly the data they need.
- Real-Time Data Needs: If real-time data updates are crucial, GraphQL subscriptions provide a powerful mechanism for real-time data synchronization between the server and clients.
- Single Page Applications (SPAs): For SPAs where optimizing network requests is crucial, GraphQL can reduce over-fetching of data, improving performance.
- Microservices Architecture: GraphQL is well-suited for micro services environments, where different services may expose different types of data, allowing clients to aggregate information efficiently.
- Mobile Applications: In mobile applications, where minimizing data transfer is critical for performance and battery life, GraphQL’s fine-grained control over data retrieval is advantageous.
When to Use OData
- Enterprise-Level Applications: In large enterprise applications with existing OData services or legacy systems that support OData, it may be more straightforward to continue using OData.
- Query Optimization and Caching: OData’s query options for filtering, sorting, and paging can be highly efficient, especially when working with large datasets. Additionally, caching can be effectively implemented.
- Metadata-Driven Development: OData’s metadata capabilities are valuable when dynamic discovery of API structure is needed.
- Batch Operations: In scenarios where batch operations are essential, OData provides built-in support, simplifying complex data operations.
- Strongly-Typed Environments: In environments where a strongly-typed data model is preferred, OData’s use of the Entity Data Model (EDM) aligns well with this paradigm.
- Existing OData Ecosystem: When integrating with existing systems, services, or ecosystems that already support OData, it makes sense to continue using OData to leverage existing infrastructure.
Apollo Client:
Apollo Client is a JavaScript library used to consume GraphQL APIs. It manages queries, caching, and state management efficiently.
Consuming GraphQL in SAP UI5 application:
- Set up the project:
- Create a new SAPUI5 project using SAP Business Application Studio or a local setup.
- Initialize an SAPUI5 app using ui5 init (if using OpenUI5).
- Install Apollo Client:
Run the following command inside your SAPUI5 project to install Apollo Client and GraphQL
“npm install @Apollo/client graphql”
Configure Apollo Client in SAPUI5:
We need to set up Apollo Client to communicate with the GraphQL API.
Create a new file apollo.js inside the webapp folder and add the following code:
apollo.js:
Include Apollo Client in index.html :
Modify your index.html file to include the Apollo Client CDN:
<script src=”https://unpkg.com/@apollo/[email protected]/core/core.umd.js“></script>
<script src=”https://unpkg.com/@apollo/[email protected]/cache/cache.umd.js“></script>
<script src=”https://unpkg.com/[email protected]/graphql.min.js“></script>
Fetch Data from GraphQL API in SAPUI5:
Modify Component.js to import and use Apollo Client:
Display GraphQL Data in SAPUI5 Table:
Modify View1.view.xml to include a Table:
Bind Data to the Table in Controller:
Modify View1.controller.js to fetch data and bind it to the table:
Run and Test the Application:
Start the SAPUI5 application using npm start or run it in SAP Business Application Studio.
The table should now display country data fetched from the GraphQL API.
Conclusion:
In this blog we have installed ApolloClient in an SAPUI5 application, connected to a GraphQL API and fetched data displayed in the table. This integration allows SAPUI5 applications to fetch only the necessary data, optimizing performance and flexibility. Further we can also explore complexity queries by connecting with systems like AWS cloud etc.