Skip to content

GraphQL Examples

Node.js

The following example will get 2 Blog Posts from the Bucket Simple React Blog.

  1. Install axios
npm install axios
  1. Add the following code to a file titled index.js
// index.js
const axios = require('axios')
axios
.post('https://graphql.cosmicjs.com/v3', {
query: `{
getObjects(
bucket_slug: "simple-react-blog"
input: {
limit: 2
query: { type: "posts" }
}
){
objects {
title
}
total
}
}`
})
.then(function (response) {
const objects = response.data.data.getObjects
console.log(objects)
})
.catch(function (error) {
console.log(error)
})
  1. 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.

  1. Install Apollo packages
npm install apollo-boost graphql
  1. Create a file titled index.js and add the following example code:
// index.js
import 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 {
title
content
}
total
}
}
`
})
.then(result => {
console.log(result)
document.getElementById('root').innerHTML = JSON.stringify(
result.data.getObjects
)
})
  1. Install webpack-cli
npm i -g webpack-cli
  1. Create a file titled webpack.config.js
// webpack.config.js
const path = require('path')
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
}
  1. 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>
  1. Run webpack
webpack
  1. View the index.html file in a browser.