Interacting with GraphQL API
Python
Docker Job setup for fetching Data from GraphQL API
through Python.
from qlient import Client, GraphQLResponseclient = Client("https://swapi-graphql.netlify.app/.netlify/functions/index")res: GraphQLResponse = client.query.film(# swapi graphql input fieldsid="ZmlsbXM6MQ==",# qlient specific_fields=["id", "title", "episodeID"])print(res.query) # query film($id: ID) { film(id: $id) { id title episodeID } }print(res.variables) # {'id': 'ZmlsbXM6MQ=='}print(res.data) # {'film': {'id': 'ZmlsbXM6MQ==', 'title': 'A New Hope', 'episodeID': 4}};
Let’s see what each field in the above job means:
Select Docker Job Type
This is Docker Job Type selection in which we have to select what kind of docker job we are creating.
Default
Job Name
This is just a job name for reference. You can use any name you want to specify for this job.
FetchingThroughAPI
Input File Name
Name of the input file you want to run in code widget. In our case, it is main.py
.
main.py
Input File Name is the name of the file that will compile or run. The one the user will write their code in. Once its name is set that file shows up in the code widget and is used by default.
Run Script
This script runs when we execute the code in the code widget. It is mandatory.
python3 main.py
Now that our client environment is all setup, we make a code widget, and select the job name set for FetchtingThroughAPI as illustrated below:
Go ahead and Run the below code. You should see a file named as main.py
in the output window, available for download.
Let’s run an example
from qlient import Client, GraphQLResponseclient = Client("https://swapi-graphql.netlify.app/.netlify/functions/index")res: GraphQLResponse = client.query.film(# swapi graphql input fieldsid="ZmlsbXM6MQ==",# qlient specific_fields=["id", "title", "episodeID"])print(res.query) # query film($id: ID) { film(id: $id) { id title episodeID } }print(res.variables) # {'id': 'ZmlsbXM6MQ=='}print(res.data) # {'film': {'id': 'ZmlsbXM6MQ==', 'title': 'A New Hope', 'episodeID': 4}};
Code Breakdown
On Line 1 we are importing the required libraries to interact with GraphQL API.
On Line 3 we are creating a connection with GraphQL API.
From Lines 5-11
we wrote Query to fetch data from GraphQL API. id
represents the key
against which we want to fetch data._fields
stores the column we want to retrieve.
From Lines 13-15 we wrote commands for printing results we received against our query.