The problem came from graphql-python , which escaped the double escape
It can be solved with something like this:
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import demoji
gql_transport=RequestsHTTPTransport(
url='https://check-api.checkmedia.org/api/graphql',
headers={'Content-Type': 'application/json', 'X-Check-Token': 'secret_token'},
)
gql_client = Client(
transport=gql_transport,
fetch_schema_from_transport=True, # increases loading time
)
updated_description = 'My new description \\n On several lines and 🤔emoji... '
# query string and replace with query parameter values. Because of the curly brackets in the json, we can't use the usual string.format()
query_string = '''
mutation {
updateProjectMedia( input: {
project_id: %s,
clientMutationId: "1",
id: "%s==\\n",
metadata: "{\\"description\\": \\"%s\\"}"
}) {
project_media {
title
description
id
}
}
}
'''% (list_dbid, media_id, updated_description)
gql_query = gql(query_string)
# locate the metadata argument in the qgl_query object and edit the string inplace
gql_query_fields = gql_query.definitions[0].selection_set.selections[0].arguments[0].value.fields
for gql_field in gql_query_fields:
if gql_field.name.value == 'metadata':
# gql_field.value.value is the target string of value:
# '{"description": "My new description \n On several lines and 🤔emoji... "}'
# notice that double escape on \n has been escaped by gql_query and needs to be added again
gql_field.value.value = gql_field.value.value.replace('\n', '\\n')
gql_field.value.value = gql_field.value.value.replace('\t', '\\t')
gql_field.value.value = gql_field.value.value.replace('\s', '\\s')
# line below attempts to escape emojis but yields [TypeError: Object of type 'bytes' is not JSON serializable] when query is executed
# gql_field.value.value = gql_field.value.value.encode('unicode-escape')
# As workaround excepttions, delete emojis
gql_field.value.value = demoji.replace(gql_field.value.value, '') # TODO escape emojis instead of deleting
response = gql_client.execute(gql_query)
When emojis are left as such in the description response = gql_client.execute(gql_query)
will return *** Exception: {'message': 'no "data" or "errors" in response from origin'}
Just like \n it seems that they need to be escaped, but encoding(‘unicode-escape’) does not work on JSON types
So I have I have to delete emojis for now. Alternatives for how to handle them are welcome!