GraphQL Error: "Unexpected token 'E', \"Expected X\"... is not valid JSON"

Question:
I’m writing GraphQL code but I’m getting the error above. This is my code:

{
  Repl(url: "https://replit.com/@masfrost/replit-gql-schema") {
    user,
    title
  }
}

I could not understand the error. I’m using @masfrost’s replit-gql-schema repl as a reference for the schema.

What am I doing wrong?

I would appreciate any help.

That’s not valid GraphQL

1 Like

try this

{
  repl(url: "https://replit.com/@masfrost/replit-gql-schema") {
    ... on Repl {
      user {
        username
      }
      title
    }
  }
}
1 Like

I’m still getting the same error.

Then please send your code

1 Like

Here it is:

{
  repl(url: "https://replit.com/@masfrost/replit-gql-schema") {
			... on Repl {
      	user {
        	username
	    	}
        
      	title
    }
  }
}

Your entire code is just that? Not sending any requests or anything? Just throwing that into a repl and hoping for the best?

1 Like

try this in a python repl:

"""file that handles posting to replit graphql endpoint for queries and mutations"""

import json
from requests import post as _post, get as _get, delete as _delete
from typing import Dict, Any, List
from time import sleep
import logging
import random
import os

backup: str = "https://graphql-playground.pikachub2005.repl.co/"
endpoint: str = "https://replit.com/graphql"
headers: Dict[str, str] = {
    "X-Requested-With": "replit",
    "Origin": "https://replit.com",
    "Accept": "application/json",
    "Referrer": "https://replit.com",
    "Content-Type": "application/json",
    "Connection": "keep-alive",
    "Host": "replit.com",
    "x-requested-with": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0",
}
number_convert: List[str] = ["1st", "2nd", "3rd"]
__reset_status_codes: List[int] = [429, 403, 520, 503, 502, 500]
GREEN = green = "\033[0;32m"
BLUE = blue = "\033[0;34m"
PURPLE = purple = "\033[0;35m"
RED = red = "\033[0;31m"
END = end = "\033[0m"
BOLD_GREEN = bold_green = "\033[1;92m"
BOLD_BLUE = bold_blue = "\033[1;94m"

def post(
    connection: str,
    query: str,
    vars: Dict[str, Any] = {},
    retry_for_internal_errors: bool = True,
    __different_endpoint: str = None,
):
    """post query with vars to replit graph query language"""
    _headers = headers
    _headers["Cookie"] = f"connect.sid={connection}"

    class InitialRequest:
        def __init__(self):
            self.status_code = 429
            self.text = ""

    req = InitialRequest()
    number_of_attempts = 0
    max_attempts = 7
    if __different_endpoint is None:
        __different_endpoint = endpoint
    while (
        req.status_code in __reset_status_codes or str(req.status_code).startswith("5")
    ) and number_of_attempts < max_attempts:  # only try 7 times
        current_endpoint = f"{__different_endpoint}?e={int(random.random() * 100)}"
        req = _post(
            current_endpoint,
            json={"query": query, "variables": vars},
            headers=_headers,
        )
        if req.status_code in __reset_status_codes or str(req.status_code).startswith(
            "5"
        ):
            N_TH = (
                number_convert[number_of_attempts]
                if number_of_attempts < 3
                else str(number_of_attempts + 1) + "th"
            )
            logging.warning(
                f"{green}[FILE] POST_QL.py{end}\n{red}[WARNING]{end}\n{red}[STATUS CODE] {req.status_code}\n\t{red}[INFO]{end} You have been ratelimited\n\t{bold_blue}[SUMMARY]{end} Retrying query for the {N_TH} time (max retries is 5)"
            )
            number_of_attempts += 1
            sleep(
                5 * (number_of_attempts)
            )  # as not to overload the server, the sleep time increases per num attempts
            continue
        vars_max = 200
        query_max = 100
        text_max = 200
        _query = query
        _vars = (
            f" {vars}"
            if (len(json.dumps(vars, indent=8)) + 3 >= vars_max or len(vars) <= 1)
            else f"\n\t\t\t{json.dumps(vars, indent=16)[:-1]}\t\t\t" + "}"
        )
        _text = req.text.strip("\n")
        if len(_vars) >= vars_max:
            _vars = _vars[: vars_max - 3] + "..."
        if len(_query) >= query_max:
            _query = _query[: query_max - 3] + "..."
        if len(_text) >= text_max:
            _text = _text[: text_max - 3] + "..."
        if req.status_code == 200:
            logging.info(
                f"{green}[FILE] POST_QL.py{end}\n{green}[INFO]{end} {bold_green}Successful graphql!{end}\n\t{blue}[SUMMARY]{end} queried replit's graphql with these query and vars.\n\t{purple}[EXTRA]{end}\n\t\t{bold_blue}[QUERY]{end} {query}\n\t\t{bold_blue}[VARS]{end}{_vars}\n\t\t{bold_blue}[RESPONSE]{end} {_text}\n\t\t{bold_blue}[IS RAW QUERY]{end} {raw}\n\t\t{bold_blue}[URL END POINT]{end} {current_endpoint}"
            )
        else:
            return logging.error(
                f"{red}[FILE] POST_QL.py{end}\n{red}[STATUS CODE] {req.status_code}\n\t{purple}[EXTRA]{end} {_text}\n\t\t{bold_blue}[QUERY]{end} {query}\n\t\t{bold_blue}[VARS]{end}{_vars}\n\t\t{bold_blue}[URL END POINT]{end} {current_endpoint}\n\t\t{bold_blue}[RETRY]{end} {retry_for_internal_errors}"
            )
        res = json.loads(req.text)

        try:
            _ = list(map(lambda x: x["data"], list(res["data"])))
            return _
        except:
            if "data" in res["data"]:
                return res["data"]["data"]
            else:
                if "data" in res:
                    return res["data"]
                else:
                    return res
x = post("", """query Repl($url: String) {
    repl(url: $url) {
        ...on Repl {
            user {
                    username
            }
            id
            title
        }
    }
}""", vars={"url": "https://replit.com/@masfrost/replit-gql-schema"})
print(x)

Hello @TheNoobKing

It looks like the code you’ve provided is not a valid GraphQL query, but rather a JavaScript object. It seems like you are trying to use GraphQL to fetch data from a Replit endpoint, but the endpoint doesn’t return valid GraphQL data. Instead, it returns JSON data, which can be accessed using regular HTTP requests, such as the fetch() function in JavaScript or the requests library in Python.

Here’s an example of how you can use the requests library in Python to fetch data from the endpoint:

import requests

url = "https://replit.com/@masfrost/replit-gql-schema"
response = requests.get(url)
data = response.json()

print(data)

This will return the JSON data from the endpoint, which you can then parse and use in your program.

Alternatively, you can use the fetch() function in JavaScript to fetch data from the endpoint:

fetch("https://replit.com/@masfrost/replit-gql-schema")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

This will return the JSON data from the endpoint, which you can then parse and use in your program.

It seems like the endpoint is returning the source code of the repl instead of the actual data, thus the error message. You should check the documentation of the endpoint, or contact the developer of the endpoint to figure out the correct way to access the data you’re looking for.

let me know if it helps.

hope it helps! :slight_smile:

hey there, that url is actually just a repl and will return no gql response

in addition, you need to post to https://replit.com/graphql

ok @bigminiboss did you try the provided examples??

yes; in my code, an example is provided at the bottom.

EDIT: sorry I misunderstood; your example will attempt to request data from replit itself, not the gql. TheNoobKing is asking about gql, instead your example will return a web page response.

@CodingCactus I’m experimenting in the GraphQL playground, I’m just not sure why the query doesn’t work (I’m still figuring GQL out).

@bigminiboss @bil0009 thanks for the answers.

@TheNoobKing in which graphql playground are you experimentig this query?
I think we can’t do any query in the graphql playground located at https://replit.com/graphql, but it should works here with this query (from @CodingCactus )

{
  repl(url: "https://replit.com/@masfrost/replit-gql-schema") {
    ... on Repl {
      user {
        username
      }
      title
    }
  }
}

The query doesn’t work becasue I have formatted it in a way that needs to be used in python or some language with fetch requests, not gql playground. Please use nathanTi’s answer :smiley: for gql playground