knuckleswtf / scribe

Generate API documentation for humans from your Laravel codebase.✍
https://scribe.knuckles.wtf/laravel/
MIT License
1.7k stars 303 forks source link

How to mark a property of response as nullable and / or required when using `ResponseFromApiResource` attribute class? #624

Open matrixhcl opened 1 year ago

matrixhcl commented 1 year ago

My team heavily rely on openapi generator: https://github.com/OpenAPITools/openapi-generator , to generate a type-safe interface from openapi documentation for our frontend typescript project to call API.

For request parameter, this library did a really good job on generate sound request interface. But for response, I struggle on creating a reliable response interface with #[ResponseFromApiResource] Attribute.

The issue I am facing is that, when converting a open api endpoint response to interface, all openapi generator tools I use will mark object properties as optional, if it's not marked as required. For example, for a response with structure like this:

type: object
properties:
  cost_ratio:
    type: number
    example: 1.2
  ms_team_webhook_url:
    type: string

would end up generate an interface in typescript like this:

interface TestObject {
  cost_ratio?: number;
  ms_team_webhook_url?: string;
}

The question-mark indicates that the field is possibly undefined, which is not the case for most of our API response. so we need to update the schema like this:

type: object
required:
  - cost_ratio
  - ms_team_webhook_url
properties:
  cost_ratio:
    type: number
  ms_team_webhook_url:
    type: string

It's similar for nullable fields.

I don't expect this library to automatically add these required attributes for me, as I know that's really hard to determine if a field is nullable / required merely by reading the resource file, after all it's not a type-hinted file like a typescript interface. But it seems that there's no way to add it manually too. Did I miss something or it's currently impossible to do so?

shalvah commented 1 year ago

Hmm, did you try adding a responseField annotation for those fields you want to customise?

matrixhcl commented 1 year ago

I did check the documentation on https://scribe.knuckles.wtf/laravel/documenting/responses#response-fields , but can't figure out the correct syntax to do so. It seems that all I could do is adding property type, but I cannot mark property as required or nullable. The ResponseFromApiResource Attribute doesn't support this use case too, I suppose?

shalvah commented 1 year ago

Not looked at this in detail, but I remembered something: we don't currently support things like required/nullable on response properties. The OpenAPI spec wasn't the primary use case.