From API to Database: Is letting clients declare the data they need the ultimate form of a data service?

November 24, 2026

“The database already knows how the tables relate. Why write an API for every page?” I've been thinking about that for a long time. My interest in reusing models may come from my earlier experience with Caché. In a presentation I used a patient class as an example: the program could open a patient record by ID with %OpenId(), and SQL could retrieve the very same record. Both ways of reading shared a single definition. I wondered whether that definition could extend all the way to the HTTP request from a page. Caché object access and SQL tables

Later, while building an asset management console, I needed a user list with both names and permissions. Once again I wrote backend code to fetch users, look up permissions and assemble the results by person. 1 The page's requirement fit in one sentence: “I want this page of users, together with each person's permissions.” If the client could express that directly, the backend could let a framework assemble the data.

How far have public implementations come?

APIJSON's author ran into a similar problem. A profile page needed user information and recent albums, while another page might need only the username. Add albums to the user endpoint and the second page gets photos it never uses. Create an endpoint for the profile page and the next combination needs backend work again. APIJSON lets both pages specify what they need in their requests. 2 Other public implementations also give clients choices, though their fields and relationships come from different places.

ApproachHow the page expresses its needsWho finds the data
FalcorTreat remote data as one large JSON object and fetch values by path.The server maps paths to data sources. The client can also reuse its local cache. 3
GraphQLSelect fields from the types the server publishes, following them level by level.The server supplies field resolution logic, which can query a database or call an existing service. 4
Hasura GraphQL Engine v2The client writes a GraphQL query.The engine generates a GraphQL API from exposed tables and relationships. Developers can manually configure relationships the database does not declare. 5
PostgRESTSpecify columns and related resources in the URL's select parameter.The service reads declared PostgreSQL foreign keys and generates join conditions for this request. 6
APIJSONUse JSON to specify tables, fields, conditions and which value from another record to use in the query.The backend interprets the conventions, validates requests, executes database operations and organizes the results accordingly. 7

Grey Zeng's Java example already supported querying posts. Send {"Moment":{"id":12}} to POST /get and the service returns post 12. Now the database has a new rough-stone table, b_stone, with an id, cost and selling price. How can the same /get query it? 8

The server first defines a class annotated with access rules. Its class name, Stone, is the name clients use when requesting stones. I've adapted the example below to show only the read configuration. 8

// Stone.java
@MethodAccess
public class Stone {
}

Next, when initializing DemoSQLConfig, associate that name with the database table and register the class's access rules:

String apiName = Stone.class.getSimpleName();  // "Stone"
TABLE_KEY_MAP.put(apiName, "b_stone");

MethodAccess rules = Stone.class.getAnnotation(MethodAccess.class);
AbstractVerifier.ACCESS_MAP.put(apiName, getAccessMap(rules));

The table-name mapping solves a specific problem: the request says Stone, but the database table is named b_stone. After restarting the example service, we can compare the queries. Both are HTTP POST requests to the same /get. The name in the body determines the table, and id selects the record.

url='http://localhost:8080/get'

# 查第 12 条动态
curl -H 'Content-Type: application/json' -d '{"Moment":{"id":12}}' "$url"

# 查第 1 块原石
curl -H 'Content-Type: application/json' -d '{"Stone":{"id":1}}' "$url"

The original response to the second request includes "Stone":{"id":1,"cost":2,"price":3} (excerpt). The additions are a table-name mapping and access rules. The existing /get still processes the query. 8

Conventional object-relational mappers (ORMs) can already read models from a database and help the backend construct queries. 9 When the client can select fields, that model gains a second consumer. Backend code knows which column to join on. What name does a page developer use to select the relationship?

What is a foreign key called on the client?

The PostgREST documentation has an example in which an order's billing and shipping addresses both point to the same address table. Reading the database foreign keys reveals two possible joins. Clients requesting an address can specify the foreign key, so shipping lists can retrieve the shipping city and invoices can retrieve the billing city. 6

erDiagram
    Orders {
        int id PK
        int billing_address_id FK
        int shipping_address_id FK
    }
    Addresses {
        int id PK
        string city
    }
    Orders }o..o| Addresses : "billing_address_id"
    Orders }o..o| Addresses : "shipping_address_id"

This entity-relationship diagram simplifies the PostgREST order example. PK means primary key, which identifies a record. FK means foreign key. Both address IDs on the order point to the address table's primary key id. Which line to follow depends on whether the city column is for the person preparing the invoice or the person shipping the order. 6

Looking back, I may have been comparing APIJSON and GraphQL to answer one question: when someone building a page says “I want the shipping city for each order,” which language makes that easier to express? Suppose the GraphQL API names the two fields on an order billingAddress and shippingAddress. The query for a shipping list is:

{
  orders {
    id
    shippingAddress { city }
  }
}

Replace shippingAddress with billingAddress, and the invoicing page gets the city from the billing address. The page developer only needs the two relationship names. The server connects them to the corresponding foreign keys. 4 GraphQL's official guide recommends naming relationships with the language the team uses in everyday business. The shipping team says “shipping address,” so the query uses shippingAddress. 10

How would APIJSON express the same shipping list? Suppose the server exposes the diagram's tables as Orders and Addresses, keeping the column names in the diagram. The following adapts an official APIJSON relationship-query example. 7

{
  "[]": {
    "Orders": { "@column": "id,shipping_address_id" },
    "Addresses": {
      "id@": "/Orders/shipping_address_id",
      "@column": "city"
    }
  }
}

[] requests a set of records, and @column lists the columns. First get each order's number and shipping-address ID. Then read id@ under Addresses: match the shipping_address_id just obtained to an address id and retrieve that address's city. These conventions in JSON keys form APIJSON's domain-specific language (DSL). This form also returns the address ID used in the relationship.

To change to an invoice list, a GraphQL query only replaces shippingAddress with billingAddress because the server already defines both relationships. In the APIJSON request, change both occurrences of shipping_address_id to billing_address_id. The page developer needs to know the foreign-key column name, which also allows them to say directly which column to use.

Their defaults also differ when selecting return fields. In a 2018 comparison, TommyWhite used user details as an example. GraphQL names each desired field. In the article's APIJSON example an object returns all fields by default. Only when requesting just the ID and name do you write "@column":"id,name". Thus APIJSON requests may be shorter for detail pages that use nearly every field. When a list uses only two columns, both syntaxes can specify exactly which ones. 11

If I designed a JSON interface for selecting fields, I'd borrow -> from Caché SQL. In hospital reports, OEORD_Adm_DR->PAADM_Type reads as “follow this order's encounter reference and get the encounter type.” The left side selects the relationship, and the right side names the field. Returning to orders, imagine an API that accepted this shipping-list request:

{ "Order": { "fields": ["id", "shippingAddress->city"] } }

The fields and arrow here are my proposed syntax. Swap shippingAddress->city for billingAddress->city and the same address table answers both “which city receives the goods?” and “which city receives the bill?” The server generates a join from the relationships exposed in the order model. The page doesn't even need the name of the address table. How Caché arrows expand to JOINs

Is declaring which records to create enough to complete a write?

A query can follow an existing ID to another record. Writes introduce a complication: the referenced ID may not exist yet. Searching for “APIJSON multi-table insert,” I found a geofence example. Each fence has a database-generated integer ID. A coordinates table uses fence_id to record which fence each point belongs to. How can the client save a new fence and its coordinates together? 12

The person asking included these two objects in an APIJSON 5.0 request. Here are the fence name, coordinates and relationship field from the example. 12

{
  "Fence": { "name": "test" },
  "FenceLoc": { "fence_id": "Fence/id", "axis_x": 1, "axis_y": 1, "axis_z": 1 }
}

They wanted fence_id to take the newly created fence ID. APIJSON denotes references with keys containing @, but their request used an ordinary fence_id key. These are the two SQL statements in the log, reformatted and with the database name omitted. 712

INSERT INTO tb_fence (name, customer_id)
VALUES ('test', 1);

INSERT INTO tb_fence_loc (fence_id, axis_x, axis_y, axis_z, customer_id)
VALUES ('Fence/id', 1, 1, 1, 1);

If the first insert generated ID 42, the first value in the second insert should be the integer 42. Instead it received the string 'Fence/id', causing MySQL to report an error writing the integer column. The issue includes the failure log but no successfully verified APIJSON request. 12

With Hasura v2 and PostgreSQL, the same requirement can be expressed as a nested insert. This simplified adaptation of the official example has a fence table with an auto-incrementing id and a name. The coordinates table has fence_id and three numeric coordinates. Hasura calls the one-to-many relationship from a fence to its coordinates points. The client can write: 13

mutation CreateFence {
  insert_fence_one(object: {
    name: "test"
    points: { data: [{ axis_x: 1, axis_y: 1, axis_z: 1 }] }
  }) {
    id
    points { fence_id }
  }
}

Points in points.data belong to the fence being created, so the input can omit fence_id. Hasura inserts the fence, obtains the generated ID and uses it for the coordinate rows. The trailing id and points { fence_id } specify the return fields. If the new ID is 42, both will return 42. The two writes share a PostgreSQL transaction. If a coordinates row violates a constraint, the fence row rolls back too. When reading, the foreign key tells the framework which columns to follow. When writing, nested data also tells it “create these records together this time.” 13

Sending three coordinates means something clear when creating a new fence. On an existing fence it might mean appending three points or replacing all the original points. The foreign key suffices to associate points with the correct fence. The schema alone cannot tell us which operation is intended or whether the user may perform it.

If clients can select fields, who decides read and write permissions?

Consider purchase price. An employee doing inventory and a manager checking prices can open the same asset details page. When doing inventory, the manager requests only the asset name, selecting purchase price too when checking prices. Even if an ordinary employee sends exactly the same request, they can read only the columns exposed to them. Which assets a role can see, which fields it can see on them, and whether it can change prices are three separately grantable permissions.

Hasura v2 lets you select queryable, insertable and updatable columns independently for each role. 14 PostgREST can switch to the appropriate PostgreSQL role after authentication and have the database enforce column privileges. An easy detail to miss: if employees already have table-wide read permission, revoking the grant on the purchase-price column alone leaves the table-wide permission in effect. Configure column-level permissions starting with the columns people may actually read. 15 APIJSON's author also demonstrated a different arrangement, separating public user profiles from private information and setting role-specific rules for each. 16

If a data service can generate APIs, why do we still need a backend?

Suppose a buyer clicks “Place order with supplier.” The data service can validate permissions and fetch the approved purchase order, item details and shipping address from its database. The page can now display a complete purchase order, yet the supplier has received nothing. The backend still needs to convert the details into the supplier's format, submit them using company credentials and record the supplier's order number locally after receiving acknowledgement.

The tricky case is when the supplier may have accepted the order but the acknowledgement times out. Rolling back a local database transaction cannot withdraw an accepted order from the supplier. The backend must reconcile the result with the order identifier agreed by both sides and decide whether to retry so the same goods aren't ordered twice. Those conventions come from the supplier's API and procurement process. They cannot be inferred from the local schema.

I think these services can automate most conventional single-database requirements. Pagination, filtering, joins, authorized CRUD and transactional writes of master and detail rows can all share an implementation once the model and rules are defined. The business backend still has to decide who receives the data, what counts as acceptance, and how to finish the job when something goes wrong.

The product I'd like: generate a data service from a database

I'd start by having such a product read all tables, column types and foreign keys in a relational database, then generate GraphQL types, fields and relationship names by convention. For shipping_address_id, strip _id and convert to camel case to get shippingAddress. Even if the columns are only address_id_1 and address_id_2, the tool can name both relationships. Developers can supply business aliases if the names are hard to understand.

Those names are ultimately for people building pages. In Comparing GraphQL, Falcor and APIJSON, the blogger 世界这么美还没钱去看 also notes that fetching data in one go reduces requests and lets clients choose the return structure. I agree on both points. As for syntax, the author proposes “参考GraphQL的语法,实现json的GraphQL。” (use GraphQL syntax as a reference to implement a JSON version of GraphQL). 17 I'd stick with native GraphQL: shippingAddress { city } tells me I'm requesting the shipping city. The author also worries that a type system adds to the backend learning curve. I value precisely the types and relationships the database already defines. The service can generate its query model from them, leaving the team to maintain the business meanings that need additional explanation.

The author also says that plugging APIJSON into an existing framework might require rewriting even the JSON-to-SQL conversion. Their idea was to offer parser extension points. I would give the product a narrower responsibility. 17 A readable foreign-key name needs only an alias. If a requirement makes me specify how to fetch every field and write the joins myself, I'd prefer to write that query directly in a business service using an established ORM. The query logic has to exist anyway. Translating it again into mapping rules for a generic interface adds code to maintain. What attracts me to the product is being able to use the relationships the schema already expresses.

The same model can generate writes for related data. The caller selects create, append or replace, and the service handles ordering, passing on new IDs and committing or rolling back a single transaction. Business actions require another layer of agreement. For example, the procurement service defines which identity can approve a purchase, which state permits approval and what approval record must be left.

Generated operations cover a lot of ground. I'd like to review which roles can use which operations in Git, much like managing infrastructure with Terraform, then apply the permissions to the database during deployment. Web pages, import scripts and background jobs would use their own roles, with the database enforcing the same authorization policy. The tool should also compare configuration with actual grants. If someone temporarily opens table-wide reads, the next check can flag that employees can now read the previously restricted purchase price. 18

I would also limit each query to a single database. When reimbursements live in the finance database and names in the directory, the client or business service can query each and combine them by employee ID. A general-purpose engine returning both in one response would also need to know which identifier joins them and whether it should return partial results if the directory times out. A finance page might show amounts and order numbers first, while a report requiring complete attribution may need to wait for all the names. The same two sources require different behavior depending on the use. Leaving those few lines of composition to the caller gives the database service a clear responsibility.

Is letting clients declare the data they need the ultimate form of a data service? For modeled and authorized data within one database, my answer is close to yes. If tomorrow a page needs another column or one more level of an existing relationship, it can change its own query. When the requirement becomes “who may change a price?” or “under what conditions is this approved?”, the change also has a clear home: authorization for the first, business rules for the second.

Footnotes

  1. S2thend. (2025, May 7). AssetMan [源代码,提交 44632fb]. GitHub. 权限表定义;用户与权限列表查询。 ↩

  2. 孤独的探索号(TommyLemon). (2017, March 20). APIJSON-以坚持和偏执,回敬傲慢和偏见. 博客园,“一、关于开发”开头的用户资料与相册示例。原文 ↩

  3. Netflix. (n.d.). Falcor. GitHub, README. 项目说明 ↩

  4. GraphQL Foundation. (2021, October). GraphQL specification, §2.4, “Selection Sets.” 字段选择;GraphQL Foundation. (n.d.). Execution, “Field resolvers.” 字段取值 ↩ ↩2

  5. Hasura. (n.d.). Postgres: Create relationships. Hasura GraphQL Engine v2 documentation. 根据外键建立关系与手动配置 ↩

  6. PostgREST. (n.d.). Resource embedding, “Foreign Key Joins” and “Foreign Key Joins on Multiple Foreign Key Relationships.” 外键与地址示例 ↩ ↩2 ↩3

  7. APIJSON. (n.d.). APIJSON Document, “Refer a value.” GitHub. 协议与引用赋值示例 ↩ ↩2 ↩3

  8. Grey Zeng. (2021, January 22). APIJSON简单使用. 博客园,“测试”和“新增一个接口”小节。原文建表名为 b_stone,映射片段写作 b_store;本文示例按建表语句统一为 b_stone,并简化了注解参数。原石表与 Stone 查询示例 ↩ ↩2 ↩3

  9. Prisma. (n.d.). What is introspection? Prisma ORM documentation. 从已有数据库生成模型 ↩

  10. GraphQL Foundation. (n.d.). Thinking in graphs, “Shared Language.” GraphQL. 用业务语言给类型和关系命名 ↩

  11. TommyWhite. (2018, May 8). 完爆Facebook/GraphQL,APIJSON全方位对比解析(一)-基础功能. 稀土掘金,“基础功能对比”中“返回字段”段及其 User 示例。原文 ↩

  12. fdw1466. (2022, April 28). 如何实现连表插入数据 [Issue #391]. GitHub, APIJSON. 请求、执行日志与讨论 ↩ ↩2 ↩3 ↩4

  13. Hasura. (n.d.). Postgres: Insert mutation, “One-to-one / One-to-many relationships,” “How it works,” steps 2–3. Hasura GraphQL Engine v2 documentation. 嵌套插入与 ID 传递顺序。Hasura. (n.d.). Multiple mutations in a request, “Execution.” 同库事务与回滚 ↩ ↩2

  14. Hasura. (n.d.). Column permissions. Hasura GraphQL Engine v2 documentation. 按角色、操作和列授权 ↩

  15. PostgREST. (n.d.). Authentication. 按请求切换数据库角色;PostgreSQL Global Development Group. (n.d.). GRANT, “Notes.” 整表授权与列授权 ↩

  16. TommyLemon. (2017). Comment on APIJSON的安全问题 [Issue #12]. GitHub. User 与 Privacy 的角色校验示例 ↩

  17. 世界这么美还没钱去看. (2021, February 25). GraphQL Falcor APIJson 对比. 博客园,“背景”、“GraphQL/Falcor”、“APIJson 动态的实现”及“总结”第 1 段(引文)。原文 ↩ ↩2

  18. HashiCorp. (n.d.). Manage resource drift. Terraform tutorials. 期望配置与实际状态的差异 ↩

© 2026 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2026-11-24). From API to Database: Is letting clients declare the data they need the ultimate form of a data service?. https://caiborui.com/blog/2026-11-24-zh-from-api-to-database-entrans

@misc{borui2026-dcdb6d42,
  author = {borui},
  title = {{From API to Database: Is letting clients declare the data they need the ultimate form of a data service?}},
  year = {2026},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2026-11-24-zh-from-api-to-database-entrans}
}