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.
- We only define a single endpoint (for example http://example/graphql).
- 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
- Create a new directory to store the project, run npm init to configure the new project
- Run npm install to create our package.json file
- Create a server.js file (entry point for our server)
-
Create the src folder and the below required folders and files:
- Create src/schema directory and an index.js file (will contain the business logic)
- Create a src/resolvers directory and an index.js file.
- 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
-
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)