Get a full fake GraphQL API with zero coding in less than 30 seconds.
I'd love to learn GraphQL, but it seems that I first have to read a book about GraphQL Types and Queries, then install a gazillion npm packages.
- About every developer
Start playing with GraphQL right away with json-graphql-server
, a testing and mocking tool for GraphQL. All it takes is a JSON of your data.
Inspired by the excellent json-server.
Follow the guide below starting from scratch, or see the example live on StackBlitz:
Create a db.js
file.
Your data file should export an object where the keys are the entity types. The values should be lists of entities, i.e. arrays of value objects with at least an id
key. For instance:
module.exports = {
posts: [
{ id: 1, title: "Lorem Ipsum", views: 254, user_id: 123 },
{ id: 2, title: "Sic Dolor amet", views: 65, user_id: 456 },
],
users: [
{ id: 123, name: "John Doe" },
{ id: 456, name: "Jane Doe" }
],
comments: [
{ id: 987, post_id: 1, body: "Consectetur adipiscing elit", date: new Date('2017-07-03') },
{ id: 995, post_id: 1, body: "Nam molestie pellentesque dui", date: new Date('2017-08-17') }
]
}
Start the GraphQL server on localhost, port 3000.
json-graphql-server db.js
To use a port other than 3000, you can run json-graphql-server db.js --p <your port here>
To use a host other than localhost, you can run json-graphql-server db.js --h <your host here>
Now you can query your data in graphql. For instance, to issue the following query:
{
Post(id: 1) {
id
title
views
User {
name
}
Comments {
date
body
}
}
}
Go to http://localhost:3000/?query=%7B%20Post%28id%3A%201%29%20%7B%20id%20title%20views%20User%20%7B%20name%20%7D%20Comments%20%7B%20date%20body%20%7D%20%7D%20%7D. You'll get the following result:
{
"data": {
"Post": {
"id": "1",
"title": "Lorem Ipsum",
"views": 254,
"User": {
"name": "John Doe"
},
"Comments": [
{ "date": "2017-07-03T00:00:00.000Z", "body": "Consectetur adipiscing elit" },
{ "date": "2017-08-17T00:00:00.000Z", "body": "Nam molestie pellentesque dui" },
]
}
}
}
The json-graphql-server accepts queries in GET and POST. Under the hood, it uses the express-graphql
module. Please refer to their documentations for details about passing variables, etc.
Note that the server is GraphiQL enabled, so you can query your server using a full-featured graphical user interface, providing autosuggest, history, etc.
npm install -g json-graphql-server
Based on your data, json-graphql-server will generate a schema with one type per entity, as well as 3 query types and 3 mutation types. For instance for the Post
entity:
type Query {
Post(id: ID!): Post
allPosts(page: Int, perPage: Int, sortField: String, sortOrder: String, filter: PostFilter): [Post]
_allPostsMeta(page: Int, perPage: Int, sortField: String, sortOrder: String, filter: PostFilter): ListMetadata
}
type Mutation {
createPost(data: String): Post
createManyPost(data: [{data:String}]): [Post]
updatePost(data: String): Post
removePost(id: ID!): Post
}
type Post {
id: ID!
title: String!
views: Int!
user_id: ID!
User: User
Comments: [Comment]
}
type PostFilter {
q: String
id: ID
id_neq: ID
title: String
title_neq: String
views: Int
views_lt: Int
views_lte: Int
views_gt: Int
views_gte: Int
views_neq: Int
user_id: ID
user_id_neq: ID
}
type ListMetadata {
count: Int!
}
scalar Date
By convention, json-graphql-server expects all entities to have an id
field that is unique for their type - it's the entity primary key. The type of every field is inferred from the values, so for instance, Post.title
is a String!
, and Post.views
is an Int!
. When all entities have a value for a field, json-graphql-server makes the field type non nullable (that's why Post.views
type is Int!
and not Int
).
For every field named *_id
, json-graphql-server creates a two-way relationship, to let you fetch related entities from both sides. For instance, the presence of the user_id
field in the posts
entity leads to the ability to fetch the related User
for a Post
- and the related Posts
for a User
.
The all*
queries accept parameters to let you sort, paginate, and filter the list of results. You can filter by any field, not just the primary key. For instance, you can get the posts written by user 123
. Json-graphql-server also adds a full-text query field named q
, and created range filter fields for numeric and date fields. All types (excluding booleans and arrays) get a not equal filter. The detail of all available filters can be seen in the generated *Filter
type.
Here is how you can use the queries and mutations generated for your data, using Post
as an example:
<tr>
<td>
<pre>
// number fields get range filters// -lt, _lte, -gt, and _gte{allPosts(filter: { views_gte: 200 }) {titleviews}}
Query / Mutation | Result |
---|---|
// get a single entity, by id { Post(id: 1) { id title views user_id } } |
{ "data": { "Post": { "id": 1, "title": "Lorem Ipsum", "views": 254, "user_id": 123 } } } |
// include many-to-one relationships { Post(id: 1) { title User { name } } } |
{ "data": { "Post": { "title": "Lorem Ipsum", "User": { "name": "John Doe" } } } } |
// include one-to-many relationships { Post(id: 1) { title Comments { body } } } |
{ "data": { "Post": { "title": "Lorem Ipsum", "Comments": [ { "body": "Consectetur adipiscing elit" }, { "body": "Nam molestie pellentesque dui" }, ] } } } |
// get a list of entities for a type { allPosts { title views } } |
{ "data": { "allPosts": [ { "title": "Lorem Ipsum", views: 254 }, { "title": "Sic Dolor amet", views: 65 } ] } } |
// paginate the results { allPosts(page: 0, perPage: 1) { title views } } |
{ "data": { "allPosts": [ { "title": "Lorem Ipsum", views: 254 }, ] } } |
// sort the results by field { allPosts(sortField: "title", sortOrder: "desc") { title views } } |
{ "data": { "allPosts": [ { "title": "Sic Dolor amet", views: 65 } { "title": "Lorem Ipsum", views: 254 }, ] } } |
// filter the results using the full-text filter { allPosts(filter: { q: "lorem" }) { title views } } |
{ "data": { "allPosts": [ { "title": "Lorem Ipsum", views: 254 }, ] } } |
// filter the result using any of the entity fields { allPosts(filter: { views: 254 }) { title views } } |
{ "data": { "allPosts": [ { "title": "Lorem Ipsum", views: 254 }, ] } } |
// all fields (except boolean and array) get not equal filters // -lt, _lte, -gt, and _gte { allPosts(filter: { title_neq: "Lorem Ipsum" }) { title views } } |
{ "data": { "allPosts": [ { "title": "Some Other Title", views: 254 }, ] } } |
{ "data": { "allPosts": [ { "title": "Lorem Ipsum", views: 254 }, ] } } |
Install the module locally:
npm install --save-dev json-graphql-server
Then use the jsonGraphqlExpress
express middleware:
import express from 'express';
import jsonGraphqlExpress from 'json-graphql-server';
const PORT = 3000;
const app = express();
const data = {
// ... your data
};
app.use('/graphql', jsonGraphqlExpress(data));
app.listen(PORT);
Useful when using XMLHttpRequest directly or libraries such as axios.
Add a script
tag referencing the library:
<script src="../lib/json-graphql-server.min.js"></script>
It will expose the JsonGraphqlServer
as a global object:
<script type="text/javascript">
window.addEventListener('load', function() {
const data = [...];
const server = JsonGraphqlServer({
data,
url: 'http://localhost:3000/graphql'
});
server.start();
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/graphql', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onerror = function(error) {
console.error(error);
}
xhr.onload = function() {
const result = JSON.parse(xhr.responseText);
console.log('data returned:', result);
alert('Found ' + result.data.allPosts.length + ' posts');
}
const body = JSON.stringify({ query: 'query allPosts { allPosts { id } }' });
xhr.send(body);
});
</script>
npm install json-graphql-server
import JsonGraphqlServer from 'json-graphql-server';
const data = [...];
const server = JsonGraphqlServer({
data,
url: 'http://localhost:3000/graphql'
});
server.start();
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/graphql', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onerror = function(error) {
console.error(error);
}
xhr.onload = function() {
const result = JSON.parse(xhr.responseText);
console.log('data returned:', result);
alert('Found ' + result.data.allPosts.length + ' posts');
}
const body = JSON.stringify({ query: 'query allPosts { allPosts { id } }' });
xhr.send(body);
import fetchMock from 'fetch-mock';
import JsonGraphqlServer from 'json-graphql-server';
const data = [...];
const server = JsonGraphqlServer({ data });
fetchMock.post('http://localhost:3000/graphql', server.getHandler());
fetch({
url: 'http://localhost:3000/graphql',
method: 'POST',
body: JSON.stringify({ query: 'query allPosts { allPosts { id } }' })
})
.then(response => response.json())
.then(json => {
alert('Found ' + result.data.allPosts.length + ' posts');
})
json-graphql-server
doesn't deal with authentication or custom routes. But you can use your favorite middleware with Express:
import express from 'express';
import jsonGraphqlExpress from 'json-graphql-server';
import OAuthSecurityMiddleWare from './path/to/OAuthSecurityMiddleWare';
const PORT = 3000;
const app = express();
const data = {
// ... your data
};
app.use(OAuthSecurityMiddleWare());
app.use('/graphql', jsonGraphqlExpress(data));
app.listen(PORT);
You can also use the export jsonSchemaBuilder
to get your own copy of the GraphQLSchema:
In node:
import {graphql} from 'graphql';
import {jsonSchemaBuilder} from 'json-graphql-server';
const data = { };
const schema = jsonSchemaBuilder(data);
const query = `[...]`
graphql(schema, query).then(result => {
console.log(result);
});
Or available in the global scope when running on a client as jsonSchemaBuilder
.
Deploy with Heroku or Next.js.
Use Prettier formatting and make sure you include unit tests. The project includes a Makefile
to automate usual developer tasks:
make install
make build
make test
make watch
make format
To learn more about the contributions to this project, consult the contribution guide.
Francois Zaninotto | Gildas Garcia | Alexis Janvier |
json-graphql-server is licensed under the MIT Licence, sponsored and supported by marmelab.
1、安装 npm install -g json-server 2、来实现一个需要简单的数据 { "gallery": [ { "id": 199, "name": "泰仪", "keyword": "泰仪", "imageUrl": "https:\u002F\u002Fehaoyao.oss-cn-hangzhou.aliyunc
json2graphql json2graphql 是一个根据 json 生成 GraphQL Schema 的工具。 可在 https://luojilab.github.io/js... 在线体验其功能。 关于 GraphQL GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并没有和任何特定数据库或者存储
json2graphql json2graphql 是一个根据 json 生成 GraphQL Schema 的工具。 可在 https://luojilab.github.io/js... 在线体验其功能。 关于 GraphQL GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并没有和任何特定数据库或者存储
使用函数 json_array_elements:将数组拆分为行 json_array_length:获取数组长度 整体逻辑 需求分析: 分页获取图像列表,images字段类型为JSON 获取images字段的总长度 实现 sql: select json_array_elements(images) from target offset 3 limit 3; select json_array
我是nodejs和qraphql的新手,我正在尝试对graphql进行简单的查询 . 在对MySQL数据库进行查询之后,我的问题是我不知道如何正确地将数据发送到graphql以查看结果 . 我必须尝试使用解决方案,但它不起作用 . 我使用json从mySQL返回结果,但它不起作用 . 为什么我在Graphiql中看不到结果?我该如何回归? 这是我进行查询并返回结果的函数: let getPlaye
--string 转 json select '{"Items":[{"Id":1,"InitStartDate":"2018-07-01T00:00:00","InitEndDate":"2018-11-13T11:46:59.461722+08:00", "CurrentStartDate":"","ProcessPercent":0,"Sta
1. 简介 postgresql9.3以后,我们可以将表的字段类型设置为json。 同时,postgresql还提供了jsonb格式,jsonb是json的二进制形式。 二者区别: json格式写入快,但读取慢; jsonb格式写入慢,但读取快。 2. 操作符 json&jsonb操作符 右操作数类型 描述 例子 结果 -> int 获取json数组的元素 ‘[{“a”:“foo”},{“b”:“
一、json like 脚本 1.json类型like用法 select * from risk_factor_attribute where risk_factor_attribute_range->>'range' like '%-%'; 2.json类型转换成text select * from risk_factor_attribute where risk_factor_attribu
一、graphql如何获取数据 每个graphql中定义的字段都有一个相关联的graphql.schema.DataFetcher。 有些字段使用自定义的data fetcher代码,用于访问数据库并从数据库中获取字段信息。而大多数字段仅使用字段名称,在内存中的Map对象或或普通的Java对象(POJO)中获取数据。 在其他的GraphQL 实现当中,Data Fetcher会有时称为resolv
前言 最近去看了看国外的题目,给打蒙了,第一道最简单的不会做,唉o(╥﹏╥)o,是一道关于GraphQL的题目,以前完全没接触过啊,一开始找到了突破点,但是一直在burpsuit尝试,这是条错误的道路啊啊啊啊,后面才了解到需要GraphQL有自己的内省查询,可以使用它的工具,啊啊啊啊,活到老学到老。 一、工具和使用网址 Introspection-GraphQL 《解析 GraphQL 的查询语法
映射数据 GraphQL将数据映射到相应类型上 GraphQL的核心思想,就是声明一种类型schema,并将它映射到运行时产生的数据上。 设计这些类型时,要充分考虑到类型与相应数据的映射方式。 例如,假设我们有如下类型: type Query { products(match : String) : [Product] # a list of products
创建示例表: DROP TABLE IF EXISTS book_info_t; CREATE TABLE book_info_t( id serial PRIMARY KEY, book_name VARCHAR(128), book_price NUMERIC(5,2), book_chapters JSONB, create_time TIMESTAMP NOT NULL DEFA
作为开发中的笔记使用。 官方文档: https://www.postgresql.org/docs/9.6/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE JSON作为Postgresql支持的语言在9.2开始支持,在9.5又增加了jsonb的数据支持。 两个可以相互转换,但是使用相关函数必须先转化。 在存储过程里可以把JSON
1、根据角码获取数组 select '[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2 结果 {"c":"baz"} 2、根据key获取json值 select '{"a": {"b":"foo"}}'::json->'a' 结果 {"b":"foo"} 3、多层纵深的查询 select '{"a":[1,2,3],"b":
您好,我正在尝试将我的graphql查询格式化为json请求,如下所示。我想以字符串形式传递id,值为“3”,当我将其作为json请求发送时,graphql会以错误的形式拒绝。我如何解决这个问题? edit1中添加的架构:`#公开指定此标量行为的URL。指令@specifiedBy( URL: String!)on|SCALAR 架构{query:RootQueryType mutation:mu
这是一个 GraphQL 服务器,支持 Express, Connect, Hapi 和 Koa 示例代码: Express: import express from 'express';import bodyParser from 'body-parser';import { graphqlExpress } from 'graphql-server-express';const myGraph
快速开始 GraphQL 是一种用于 API 的查询语言。这是 GraphQL 和 REST 之间一个很好的比较 (译者注: GraphQL 替代 REST 是必然趋势)。在这组文章中, 我们不会解释什幺是 GraphQL, 而是演示如何使用 @nestjs/GraphQL 模块。 GraphQLModule 只不过是 Apollo 服务器的包装器。我们没有造轮子, 而是提供一个现成的模块, 这让
GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。 向你的 API 发出一个 GraphQL 请求就能准确获得你想要的数据,不多不少。 GraphQL 查询总是返回可预测
GraphQL + MongoDB express server (in Typescript) This is just a starter example on how to build a GraphQL server with MongoDB database in Typescript. The advanage of this solution is a strong type che
Create GraphQL Server Create-graphql-server is a scaffolding tool that lets you generate a new Mongo/Express/Node.js GraphQL server project from the command line. After generating the project you can