A query language for your API.
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
This code represents a sample of how graphQL engine works and how powerful might be.
For this example let's imagine a simple social media, where users can make posts and comments. Check the image below:
- VSCode - IDE
- MongoDB Cloud - DB
- Postman - API Testing (optional)
Download repository
At index.js file, update information with your MongoDB's USER, PASSWORD, CLUSTER and DATABASE.
mongoose.connect('mongodb+srv:/USER:[email protected]/DATABASE');
mongoose.set('debug', true);
$ npm install
$ yarn dev
If everything works as expected, now you can play with your graphQL server.
In your Postman, send a request like this cURL below:
curl --location --request POST 'http://localhost:6666/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"{\r\n __schema {\r\n types {\r\n name\r\n description\r\n }\r\n }\r\n}","variables":{}}'
Your 200 OK response should be something like this:
{
"data": {
"__schema": {
"types": [
{
"name": "Comment",
"description": null
},
{
"name": "ID",
"description": "The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `\"4\"`) or integer (such as `4`) input value will be accepted as an ID."
},
{
"name": "String",
"description": "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text."
}
.............
mutation {
createUser (data: {
firstName: "Jane"
lastName: "Doe"
email: "[email protected]"
active: true
}) {
_id
fullName
}
}
query {
users {
fullName
active
}
}
If you find trouble to have some fun with this code feel confortable to open a new ISSUE
.
But if you find it and know how to solve, please open a PULL REQUEST
.