Skip to content

Create and Publish a GraphQL API

Follow the instructions in this tutorial to design, publish, and invoke a GraphQL API.

Note

For more information on GraphQL APIs, see Create a GraphQL API.

Step 1 - Start the GraphQL backend server

Let's use the Star Wars sample backend server as the backend for the GraphQL API.

  1. Clone the WSO2 API Manager Samples repository.

    git clone https://github.com/wso2/samples-apim
    
  2. Navigate to graphql-backend directory.

    cd samples-apim/graphql-backend
    
  3. Run npm install to install the necessary node modules.

  4. Run npm start to start the server.

    Once the above steps are done, the Star Wars server will be running on http://localhost:8080.

    CLI output

    You can use http://localhost:8080/graphql as the endpoint when creating the GraphQL API.

Step 2 - Design a GraphQL API

  1. Sign in to the API Publisher Portal.

    https://<hostname>:9443/publisher

    Example: https://localhost:9443/publisher

    Let's use admin as the username and password to sign in.

  2. Click Create API and then click Import GraphQL SDL.

    Create GraphQL Schema Option

  3. Import the schema by dragging and dropping the file or by uploading the file, and click Next.

    Let's use the StarWarsAPI schema definition to create the schema file.

    Note

    • You need to define the SDL Schema based on the GraphQL schema design best practices.

    • The file extension can be either .graphql, .txt, or .json.
    • The file name can be any name, which is based on your preference.

    Import a GraphQL schema by adding a file

  4. Enter the GraphQL API related details and click Create.

    Let's create an API named "StarWarsAPI" using the following sample data.

    Field
    Description

    Name

    StarWarsAPI

    Context

    /swapi

    Version

    1.0.0

    Endpoint

    http://localhost:8080/graphql

    Note

    • When you provide the HTTP URL as the backend endpoint, WSO2 API-M will internally derive the corresponding WebSocket URL ws://localhost:8080/graphql.
    • Thereafter, the API Gateway will use this WebSocket URL as the backend subscription endpoint of the GraphQL API.

    Add GraphQL API details

  5. Optionally, modify the existing GraphQL schema definition.

    1. Navigate to Develop, API Configurations, and click Schema Definition.

    2. Click Download Definition.

      The existing GraphQL API schema gets downloaded.

      Add schema definition

    3. Update the schema definition as required.

    4. Click Import Definition to import the updated schema definition.

  6. Update the GraphQL API operations as required.

    Instead of resources, which get populated for REST APIs, operations get populated for GraphQL APIs.

    1. Click Show More under the Operations section in the Overview page to navigate to the operations page.

      GraphQL API operations

    2. Update the operations as required.

      The Publisher can add Rate Limiting policies, scopes and enable/disable security for each of the GraphQL API operations.

      1. Create scopes.

        Repeat the following sub-steps to create two scopes named adminScope and FilmSubscriberScope.

        1. Click Local Scopes, and then click Create Scopes.

          Add a scope page

        2. Enter the required details.

          Note

          • The role that you enter should be a valid role that already exists in WSO2 API Manager. Make sure to assign the role to the user.
          • For more information, see Adding Users and Adding User Roles.

          Enter the following details for this example scenario.

          Name Role
          FilmSubscriber FilmSubscriber
          adminScope admin

          Create a scope

        3. Press Enter to add each role.

        4. Click Save.

          List of added scopes

      2. Define the operation level configurations.

        1. Click Operations.

        2. Click Operation Level to apply Rate Limiting for operations.

          Update GraphQL API operations

        3. Select a Rate Limiting Policy, scope, and enable or disable security for each of the operations.

          Apply the following scopes to the respective operations.

          Operation Scope
          allDroids FilmSubscriber
          allCharacters adminScope
        4. Click Save.

          If you check the list of scopes, it should appear as follows:

          Scope list

Now, you have created and configured the GraphQL API successfully.

Step 3 - Deploy the GraphQL API

  1. Navigate to Deploy and click Deployments to navigate to the Deploy the API page.
  2. Click Deploy to deploy the API to the API Gateway, which is the default Gateway.

    Deploy GraphQL API

    The Deployment page appears.

    GraphQL API Deployment page

Step 4 - Publish the GraphQL API

  1. Navigate to Publish and click Lifecycle.

    The API lifecycle page appears.

  2. Click Publish to publish the API to the API Developer Portal.

    Publish GraphQL API

Step 5 - Invoke the GraphQL API

  1. Sign in to the Developer Portal.

    https://<hostname>:9443/devportal

    Example: https://localhost:9443/devportal

    Let's use admin as the username and password to sign in.

    Developer Portal

  2. Click on the GraphQL API.

    The API overview appears.

    StarWarsAPI API overview

    Info

    • Note that both the HTTP and the WebSocket URLs of the Gateway are displayed for the GraphQL API.
    • The HTTP Gateway URL is to invoke the query and mutation operations of the GraphQL API.
    • The WebSocket Gateway URL is to invoke the subscription operations of the GraphQL API.

  3. Subscribe to the API.

    1. Click TRY OUT.

      Try Out Wizard and Popup

      This will create a subscription for the application named DefaultApplication and generate a consumer key and consumer secret pair for DefaultApplication. Click TRY OUT on the pop-up window to navigate to the Try Out Console.

  4. Try out the operations.

    1. Click GET TEST KEY.

      Get Test Key

Step 5.1 - Optionally, try out a Query operation

Note

  • If you are going to invoke QUERY Operation, you should start the payload with the keyword 'query'.

  • If you are going to invoke MUTATION Operation, you should start the payload with the keyword 'mutation'.

  1. Enter the following sample payload as the StarWarsAPI request. Then click on execute button as follows.

    query testQuery{
       human(id:1000){
          id
          name
       }
       droid(id:2000){
          name
          friends{
              name
              appearsIn
          }
       }
    }
    

    Execute GraphQL Query

  2. Click Execute.

    Response of GraphQL Query

Step 5.2 - Optionally, try out a Subscription operation

Note

If you are going to invoke SUBSCRIPTION operation, you should start the payload with the keyword subscription.

  1. Enter the following sample payload as the StarWarsAPI reviewAdded subscription request to get real-time updates about the addition of new reviews.

    subscription testSubscription{
       reviewAdded(episode: JEDI) {
          stars
          episode
    
          commentary
       }
    }
    
  2. Prepare to inspect the network calls from your browser developer tools.

    For example, if you are using the Google Chrome browser.

    1. Right-click on the browser and click Inspect.
    2. Click Network to view the network calls via the browser developer tools.
  3. Click Execute.

    If you inspect the network calls from your browser developer tools, you can see the messages passed between the GraphiQL client and the backend.

    Response of GraphQL Subscription Init

    As you can see, a successful WebSocket connection is established between the client and backend via WSO2 API Gateway.

  4. While keeping the Developer Portal web browser page opened, separately open a terminal and directly invoke the backend API’s createReview mutation operation by executing the following command.

    curl -X POST "http://localhost:8080/graphql" -H  "accept: application/json" -H  "Content-Type: application/json" -d '{"query":"mutation {createReview(episode: JEDI, review: { stars: 3, commentary: \"Excellent\"}) { stars   episode   commentary }}","variables":null}' -k
    

    When the mutation is successful, the GraphQL backend will send the following response:

    {"data":{"createReview":{"stars":3,"episode":"JEDI","commentary":"Excellent"}}}
    
  5. Now go back to the Developer Portal browser page.

    You can see that you have received the subscription event response that corresponds to the mutation operation you did in Step 5.2 (4).

    Response Event of GraphQL Subscription

Troubleshooting

If you cannot invoke the API's WSS endpoint during handshake (this causes the SSLPeerUnverified exception), it could be because the security certificate issued by the server is not trusted by your browser.

This will result in the following error being printed in the backend.

ERROR - InboundWebsocketSourceHandler Endpoint not found for port : 8099 tenant domain : null

To resolve this issue, access the corresponding HTTPS endpoint of the WSS endpoint directly from your browser and accept the security certificate. (e.g., https://localhost:8099/swapi/1.0.0)

If the API Manager has a certificate signed by a Certificate Authority (CA), the WSS endpoints should work out-of-the-box.

You have successfully created and published your first GraphQL API, subscribed to it, obtained an access token for testing, and tested query and subscription operations of your API with the access token.