Wrap a REST API endpoint with GraphQL in Python
Follow this tutorial to wrap a REST API endpoint with a GraphQL wrapper to make it accessible via a dedicated GraphQL API.
In this tutorial we will use a standalone Ariadne server, which is a Python library for implementing GraphQL servers. It aims to make it easy and enjoyable for developers to create GraphQL APIs by using a schema-first approach, where you define your GraphQL schema using the Schema Definition Language (SDL) and then map your resolvers to the schema.
For the REST API endpoint we will use the City Search API.
The goal of this tutorial is to create a GraphQL API, which will only use the keyword
parameter for the query and return only the name
parameter in the response.
Pre-requisites
Before you begin, you need to:
- Register your application with Amadeus for Developers as described in Making your first API call.
- Have Python installed on your machine.
Create a new Python project
- Open your terminal and create a new directory for this project:
- Navigate to the directory:
Install required dependencies
Install uvicorn
and requests
packages by running:
Define GraphQL schema
Create a schema.graphql
file with the necessary types and queries. In this tutorial, we are only using the keyword
parameter to query the City Search API and we are only interested in the name
parameters that this query returns in the response data. For this reason, our schema.graphql
will look as follows:
Create a data fetching function
Create a fetch_data.py
file and define a function that fetches data from the REST endpoint:
In the above example we are outputting logs to the console for easier troubleshooting.
Implement GraphQL resolvers
Create a resolvers.py
file and implement the resolver functions for the queries:
Set up the Ariadne server
Create the main file main.py
that sets up the Ariadne server with the schema and resolvers:
Run the server
Open the terminal and run:
Query the GraphQL API
Information
Before running the query, make sure to obtain the token as described in our Authorization guide.
Now that we have the server running, we can send requests to it. The most straightforward method to do this is by using curl
. To query this API by the keyword
"Paris":
If your token is valid, the above command will return a list of city names that contain the word Paris
.