简体   繁体   中英

“Syntax Error GraphQL request” with “&” in query

I query a database with this simple python code below. It works fine for all regions except those with "&" in the name, like "Latin America & Caribbean". When I hit these regions I get the syntax error. Could anyone suggest how to fix the problem?

My code:

import requests

def get_data(query):    
    url = "https://API_URL/graphql?query=" + query
    try:
        response = requests.get(url, cert=('xxx.crt', 'xxx.key'),  verify='xxx.crt')
        print("api responds with: HTTP " + str(response.status_code))
    except requests.exceptions.RequestException as e:
        print("-- error getting data from api: " + str(e))
    else:
        data = response.text
        print(data)
        return data


query = '''
query {
  pages(region:"Latin America & Caribbean",
    From:"May 6 2017 00:00:00 GMT+0000 (GMT)", 
    To: "May 7 2017 00:00:00 GMT+0000 (GMT)")
  {
    _id
  }

    }
'''
get_data(query)

Error:

api responds with: HTTP 400
{"errors":[{"message":"Syntax Error GraphQL request (3:48) Unterminated string.\n\n2: query {\n3:   pages(region:\"Latin America \n                                                  ^\n","locations":[{"line":3,"column":48}]}]}

& is a reserved character inside URLs, and so needs to be escaped. I believe you can utilize urllib's quote function to escape reserved and unsafe characters in your query string before appending it to the rest of your url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM