GraphQL Examples
Node.js
The following example will get 2 Blog Posts from the Bucket Simple React Blog.
- Install
axios
npm install axios
- Add the following code to a file titled
index.js
// index.jsconst axios = require("axios");axios.post("https://graphql.cosmicjs.com/v3", {query: `{getObjects(bucket_slug: "simple-react-blog"input: {limit: 2query: { type: "posts" }}){objects {title}total}}`,}).then(function (response) {const objects = response.data.data.getObjects;console.log(objects);}).catch(function (error) {console.log(error);});
- Run the following command
node index.js
Apollo
You can use Apollo Client to connect to the Cosmic GraphQL API. You will need to use a browser build system as noted on the Apollo Client README.
- Install Apollo packages
npm install apollo-boost graphql
- Create a file titled
index.js
and add the following example code:
// index.jsimport ApolloClient from "apollo-boost";const client = new ApolloClient({uri: "https://graphql.cosmicjs.com/v3",});import { gql } from "apollo-boost";client.query({query: gql`{getObjects(bucket_slug: "simple-react-blog"input: { limit: 2, query: { type: "posts" } }) {objects {titlecontent}total}}`,}).then((result) => {console.log(result);document.getElementById("root").innerHTML = JSON.stringify(result.data.getObjects);});
- Install
webpack-cli
npm i -g webpack-cli
- Create a file titled
webpack.config.js
// webpack.config.jsconst path = require("path");module.exports = {entry: "./index.js",output: {path: path.resolve(__dirname, "dist"),filename: "bundle.js",},};
- Create an HTML file titled
index.html
<!DOCTYPE html><html lang="en"><head><title>Cosmic GraphQL Apollo Example</title></head><body><div id="root"></div><script src="dist/bundle.js"></script></body></html>
- Run webpack
webpack
- View the
index.html
file in a browser.