'Why is graphcms graphql giving me a 403 error?

I created the following query in graphcms and it works in the graphql playground but when I transfer the query to my react code and try to access graphcms I get a 403 error shown below.

The query:

import { request, gql } from 'graphql-request';

const graphqlAPI = process.env.NEXT_PUBLIC_GRAPHCMS_ENDPOINT;

export const getPosts = async () => {
  const query = gql`
  query MyQuery {
    postsConnection {
      edges {
    node {
      author {
        bio
        id
        name
        photo {
          url
        }
        post {
          categories {
            name
            slug
          }
        }
      }
      createdAt
      slug
      title
      excerpt
      featureImage {
        url
      }
    }
  }
}

}

`;

const result = await request(graphqlAPI, query);

return result.postsConnection.edges;

The error:

Error: not allowed: {"response":{"errors":[{"message":"not allowed","extensions": 

{"code":"403","path":["postsConnection","edges"]}}],"data":{"postsConnection":{"edges":[]}},"status":200,"headers":{}},"request":{"query":"\n query MyQuery {\n postsConnection {\n edges {\n node {\n author {\n bio\n id\n name\n photo {\n url\n }\n post {\n categories {\n name\n slug\n }\n }\n }\n createdAt\n slug\n title\n excerpt\n featureImage {\n url\n }\n }\n }\n }\n }\n \n "}}

};



Solution 1:[1]

Just you go to the project settings in your project in GraphCMS, you can find Public Content API and there is a button which is name Yes, initialize defaults, you should click, it will work

Solution 2:[2]

I received a similar error when trying to graphcms:

Error: not allowed: {"response":{"errors":[{"message":"not allowed","extensions":{"code":"403","path":["blogPosts"]}}],"data":{"blogPosts":[]},"status":200,"headers":{}},"request":{"query":"\n {\n blogPosts {\n id,\n title\n }\n }\n "}}.

What I found that worked for me was adding the 'Read' permission to my Permanent Auth Token (PAT).

Solution 3:[3]

MDN explains a 403 Error (Not Authorized) with the following:

The HTTP 403 Forbidden response status code indicates that the server understands the request but refuses to authorize it. The access is permanently forbidden and tied to (...) insufficient rights to a resource.

This means that you need to set up your API Access configuration in GraphCMS;

  1. Visit GraphCMS
  2. Visit settings (navbar should be on your right)
  3. Under "Access", select "Public Content API"
  4. Select "Create Permission", then select the rules required for your query to run properly.

Now you can use the content API URL, for example, to run your queries.
It should be in the follwoing format;
https://<zone>.graphcms.com/v2/<identifier>/master

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Umarkhon
Solution 2 Dharman
Solution 3 Jawady Muhammad Habib