DEV Community

Derian Sibaja
Derian Sibaja

Posted on

Graphql test

Graphql API Code Cookbook

Problem

Most of the APIs request an endpoint to access a predefined data structure. If you want to access other resources, it is necessary to request another endpoint, it makes the procces kind of tricky.

  1. We only define a single endpoint (for example http://example/graphql).
  2. Since this is a query language, all actions are done through a POST.

Solution

GraphQL allow us to retrieve only the data we need by using a query language for web APIs.

Recipe

CRUD GraphQL API with Nodejs, Express & MongoDB

  1. Create a new directory to store the project, run npm init to configure the new project
  2. Run npm install to create our package.json file
  3. Create a server.js file (entry point for our server)
  4. Create the src folder and the below required folders and files:

    1. Create src/schema directory and an index.js file (will contain the business logic)
    2. Create a src/resolvers directory and an index.js file.
    3. Create an src/models directory and a post.js which holds what a post should look like.
    ├── src
    │   ├── schema
    │   │   └── index.js
    │   ├── resolvers
    │   │   └── index.js
    │   └── models
    │       └── post.js
    ├── package-lock.json
    ├── package.json
    └── server.js
    
  5. Install the dependencies

    Using npm

      # npm
      $ npm install --save express express-graphql graphql body-parser
    

    Using yarn

      # yarn
      $ yarn add --save express express-graphql graphql body-parser
    

    You can also install "nodemon" locally to avoid having to restart your server with each change

      $npm install --save-dev nodemon
    

    Also you need to update your "package.json" for using "nodemon".

      "scripts": { "start": "nodemon server.js"}
    

Top comments (0)