Learn best practices and considerations for migrating from Scope's REST API to Scope's GraphQL API.
In this article
Table of Contents |
---|
Differences in API logic
Migrating from REST to GraphQL represents a significant shift in API logic. The differences between REST as a style and GraphQL as a specification make it difficult—and often undesirable—to replace REST API calls with GraphQL API queries on a one-to-one basis. We've included specific examples of migration below.
To migrate your code from the REST API to the GraphQL API:
Review the GraphQL the GraphQL spec
Review Scope's GraphQL schema
Consider how any existing code you have currently interacts with the Scope REST API
Use Global Node IDs to reference objects between API versions
Significant advantages of GraphQL include:
Here are examples of each.
Example #1: Getting the data you need, and nothing more
A single REST API call retrieves a list of your organization's members:
...
The REST payload contains excessive data if your goal is to retrieve only member names and links to avatars. However, a GraphQL query returns only what you specify:
Code Block |
---|
query { viewer { organization(login:"Scope") { members(first: 10) { edges { node { name avatar { fileUrl } } } } } } } |
Example #2: Nesting
Querying with nested fields lets you replace multiple REST calls with fewer GraphQL queries. For example, retrieving a scenario along with its ar contents and associated groups using the REST API requires four separate calls:
Code Block |
---|
curl -v https://cms.scopear.com/api/v2/repos/:scenarios/:id curl -v https://cms.scopear.com/api/v2/repos/:scenarios/:id/attachments curl -v https://cms.scopear.com/api/v2/repos/:scenarios/:id/authoring_groups curl -v https://cms.scopear.com/api/v2/repos/:scenarios/:id/groups |
Using the GraphQL API, you can retrieve the data with a single query using nested fields:
Code Block |
---|
{
node(id: "ID_OF_SCENARIO")
... on Scenario
name
content {
fileUrl
fileContentType
fileUrlExpiresAt
}
groups {
nodes {
id
name
}
}
}
}
}
|
You can also extend the power of this query by substituting a variable for the pull request number.
Example #3: Strong typing
GraphQL schemas are strongly typed, making data handling safer.
...
Code Block |
---|
mutation {
updateScenario(id: "MDA6SXNzdWUyMjcyMDA2MTT", input:{name: 1234}) {
id
name
groups {
nodes {
id
name
}
}
}
}
|
Executing this query returns errors specifying the expected types for the operation:
Code Block |
---|
{
"data": null,
"errors": [
{
"message": "Argument 'input' on Field 'name' has an invalid value. Expected type 'String!'.",
"locations": [
{
"line": 3,
"column": 3
}
]
}
]
}
|