-
|
I am trying to implement field level security in my API. This means that the shape of the object being sent back to the client in the response can vary in shape. I don't want to take my base object and just make all the fields as optional. I would prefer to define a few different response schemas derived from a base schema. Some users will not have access to certain fields and some users will have access to all fields. I just can figure out how to keep the response validation happy. I am using Zod & fastify-type-provider-zod |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
|
I guess I could use a Zod union... |
Beta Was this translation helpful? Give feedback.
-
|
I have no idea how to do that with Zod, but you can use |
Beta Was this translation helpful? Give feedback.
-
|
I just found this!... Zod to json schema. This looks promising. |
Beta Was this translation helpful? Give feedback.
-
|
Using Zod I opted to define a base schema for each response. The base schema defines a subset of fields that are always required in the response. The remaining fields are optional, sent in response based on user access level. Provided documentation for each endpoint describing the required versus fields returned based on permissions. This idea comes from Claude 4 components:
schemas:
Account:
type: object
description: |
🔒 **Field visibility depends on user permissions.**
📋 [See Permission Matrix](https://docs.yourapi.com/permissions)
properties:
id: { type: string }
handle: { type: string }
email: { type: string }
status: { type: string }
notes: { type: string }
required: [id, handle]
# Every endpoint is clean:
paths:
/accounts/{id}:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Account'
Benefits: ✅ DRY - define schema once, reference everywhere Reality Check: Perfect OpenAPI documentation of dynamic field-level security is a pipe dream. Focus on clear, honest documentation that developers can actually use. Your TypeScript types + Zod schemas are your real source of truth for precision. |
Beta Was this translation helpful? Give feedback.
Using Zod I opted to define a base schema for each response. The base schema defines a subset of fields that are always required in the response. The remaining fields are optional, sent in response based on user access level.
Provided documentation for each endpoint describing the required versus fields returned based on permissions.
This idea comes from Claude 4