0
0

More than 1 year has passed since last update.

Python3: GraphQL サーバーにアクセスする方法

Last updated at Posted at 2022-02-20

こちらで作成した Graph QL サーバーにアクセスする方法です。
Apollo Server の使い方

プログラム

graphql_client.py
#! /usr/bin/python
#
#	graphql_client.py
#
#					  Apr/15/2023
#
# ------------------------------------------------------------------
import  sys
import  requests
# ------------------------------------------------------------------
def file_to_str_proc(file_in):
	str_out = ""
	try:
		fp_in = open(file_in,encoding='utf-8')
		str_out = fp_in.read()
		fp_in.close()
	except Exception as ee:
		sys.stderr.write("*** error *** file_to_str_proc ***\n")
		sys.stderr.write(str (ee))
#
	return  str_out
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")

file_json = sys.argv[1]
json_str = file_to_str_proc(file_json)
url="http://localhost:4000"
headers = {"Content-Type": "application/json"}
#
response = requests.post(url, headers=headers, data=json_str)
#
print(response.text)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
query.json
{
 "query": "query { books { title author }}"
}

実行結果

$ ./graphql_client.py query.json | jq
*** 開始 ***
*** 終了 ***
{
  "data": {
    "books": [
      {
        "title": "心",
        "author": "夏目漱石"
      },
      {
        "title": "舞姫",
        "author": "森鴎外"
      },
      {
        "title": "春",
        "author": "島崎藤村"
      }
    ]
  }
}

確認したバージョン

$ python --version
Python 3.10.10
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0