Making Your First API in GraphQL

Posted in

Follow this tutorial to create a simple GraphQL API

GraphQL is an intriguing way to design an API. It was developed by Facebook in 2012 for internal development and was publicly released in 2015. GraphQL is a query language for API development and is completely open-source. GraphQL is a syntax that defines how you query data in a much flexible way. It lets the client fetch the exact data it wants and makes it extremely easy to aggregate the data from different endpoints. So, in other words, you could say that GraphQL is a streamlined form of a REST API.

In REST APIs, you fetch a URL, which returns a load of JSON data for that particular resource. For instance, using the YouTube API, you could request a list of video IDs. But if you wanted information about each video, you would have to call the API repeatedly for each ID. Now imagine you have thousands of video IDs — you’d have to hit the API a thousand times, right? With GraphQL, you can perform actions like this in just one trip. You simply must define a query where you’re passing the variable, and that variable is bound to the video ID. Simple, isn’t it?

Remember one thing — GraphQL is a specification, not an implementation. You can use GraphQL on any platform. It has two parts, the server component and the client component. If an API has a GraphQL server, you just need a GraphQL client to use that API. You don’t need to learn the server-side stuff. But if you’re building full-stack apps, you need a server library as well. If you head over to their website, you’ll see that GraphQL supports many programming languages:

  • JavaScript
  • PHP
  • Go
  • Python
  • Java
  • Kotlin
  • C#
  • Ruby
  • Elixir
  • Rust
  • Swift
  • Scala
  • Flutter
  • Clojure
  • C++
  • Haskell
  • ELM
  • 0Calm
  • Erlang
  • Groovy
  • R
  • Julia
  • Perl
  • D

So far, we’ve talked a lot about GraphQL. Let’s dive into the coding part. Below, we’ll create an API that accepts the URL of a website and returns the data like title, image, and description. We’ll use Flask as the base server for the GraphQL and map the / i.e., root endpoint to the GraphQL.

Prerequisites

  • Basic knowledge of Python

Step 1: Environment Setup

Now open the terminal and create a new directory:

mkdir graphql-flask

And then, change directory:

cd graphql-flask

Now once you’re in the folder, we have to create the virtual environment. So let’s initialize one:

virtualenv .

To activate the virtual environment, use the below command. (Use source /bin/activate in case of global venv).

source bin/activate

Now, install the modules:

 pip install extraction graphene flask-graphql requests

Here we’re installing different packages like graphene, a GraphQL library that reduces the complexity of the GraphQL server by providing helper functions. We’re usingflask as the server, and graphene-flask helps connect the Flask server with the GraphQL server.

Step 2: GraphQL Schema Setup

Now it’s time to set up the GraphQL Schema. So, create a new file schema.py in the same graphql-flask directory and paste in the below code:

import graphene
import extraction
import requests

def extract(url):
    html = requests.get(url).text
    extracted = extraction.Extractor().extract(html, source_url=url)
    print(extracted)
    return extracted

class Website(graphene.ObjectType):
    url = graphene.String(required=True)
    title = graphene.String()
    description = graphene.String()
    image = graphene.String()
    feed = graphene.String()

    
class Query(graphene.ObjectType):
    website = graphene.Field(Website, url=graphene.String())

    def resolve_website(self, info, url):
        extracted = extract(url)
        return Website(url=url,
                       title=extracted.title,
                       description=extracted.description,
                       image=extracted.image,
                       feed=extracted.feed
        )

schema = graphene.Schema(query=Query)
Don’t miss our workshop with Apollo GraphQL: What If All Your Data Was Accessible in One Place

Code Explanation:

We’re importing three packages here: requests, extraction, and graphene. The extraction package here is used to extract the website data. We’re using requests here so that we can fetch the HTML page of the URL.

We have defined one function, extract(), which accepts the URL and then does all the processing. We can also use BeautifulSoup to extract data from an HTML page.

We have defined two classes, Website and Query. The class Website returns the correct data in a formatted way, while Query is used for resolving the query and returning the data to the user.

Step 3: Configuring Server for GraphQL:

Now in this step, we’ll define our GraphQL server. Create a new file server.py in the same folder and paste the below code:

from flask import Flask
from flask_graphql import GraphQLView
from schema import schema


app = Flask(__name__)
app.add_url_rule('/', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))
app.run()

Code Explanation:

We’re setting up the GraphQL server here with enabling the GraphiQL. This will help us to run the GraphQL queries. We are loading it in the root path of the server.

Step 4: Running the Server and Testing the API:

Now we’re done with the coding part. So now we can move ahead with the testing part. We can do that by running a simple command:

python3 server.py

Now open your web browser and go to URL https://127.0.0.1:5000/. You’ll see an empty GraphiQL window like this:

Now to fetch data from API, paste the below code into the left pane:

{
  website(url: "https://wikipedia.org") {
    title
    image
    description
  }
}

And you’ll get your result!! Congrats, you’ve successfully made the GraphQL API. You’ll get something like this:

{
  "data": {
    "website": {
      "title": "Wikipedia",
      "image": "https://wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",
      "description": "Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation."
    }
  }
}

Here’s what it’ll look like in your browser:

Final Words

GraphQL is a query language unlike standard REST APIs — it allows an excellent relational query system that will enable you to save trips. Other than solving the over-fetching vs. under-fetching problem, GraphQL is not much different from the REST APIs. Though GraphQL provides a lot of functionalities, REST API is still usually preferred over GraphQL. GraphQL is best for real-time applications like chat apps or live-feeds.

This was just an introduction and basic GraphQL setup — we hope you now understand some basic GraphQL concepts and can gauge whether or not to adopt something similar within your own environment.