Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override ErrorModel for single operations #401

Open
lsdch opened this issue Apr 22, 2024 · 6 comments
Open

Override ErrorModel for single operations #401

lsdch opened this issue Apr 22, 2024 · 6 comments
Labels
question Further information is requested

Comments

@lsdch
Copy link
Contributor

lsdch commented Apr 22, 2024

Currently the default error model can be overridden globally for the API. Would you consider adding a feature to set a custom error model at the level of operations ?

As far as I understand, it is already kinda possible to do so by setting the Operation.Responses, but this is cumbersome since one must provide Schema definitions instead of simply providing a Go struct type.

Operation could be extended with an ErrorModel field which would implement the StatusError interface. I am willing to try and submit a PR if this idea finds approval.

@danielgtaylor
Copy link
Owner

@lsdch you're right I don't think this is easy right now. I'm curious what the use-case is. The idea behind a single error type is that the API is consistent and predictable in how it responds, so changing the response structure of errors for a single operation is kind of counter to that idea.

You could also potentially use a Huma transformer for this (i.e. "if the operation is foo, and the response is an error, then convert it to another type") or just eschew Huma altogether and just use your underlying router directly for this one special operation, potentially manually adding docs via api.OpenAPI().Paths[...].

@danielgtaylor danielgtaylor added the question Further information is requested label Apr 25, 2024
@davidolrik
Copy link
Contributor

I was just looking for something like this for my healthz endpoints.

My use case is a /readyz endpoint that returns the status of all dependencies and an overall "are we ready to receive requests" status.

All the load balancer needs is a 200 or a 503, but the body is the same for both cases, like so:

{
    "$schema": "https://127.0.0.1:3000/schemas/ReadyzResponseBody.json",
    "checks": {
        "live": true,
        "database": true
    },
    "ready": true,
    "version": "0.42.0-1-deadbeef-devel"
}

@lsdch
Copy link
Contributor Author

lsdch commented Apr 25, 2024

My specific use case is to document an API endpoint which can respond with a fixed set of response tokens, under the same HTTP status code. Overriding the response schema for this endpoint would make explicit in the spec what content should be expected, e.g. using an enum definition.

I agree that sharing a global error model across the API is definitely desirable for consistency. The rationale for this proposal is to give the possibility to step out of the convention for some endpoints when the global model is not sufficient to document them thoroughly.

That said, after thinking a bit more about a possible implementation, I have doubts about whether this feature would play nice with Huma resolvers and ErrorXXXStatus HTTP errors

@danielgtaylor
Copy link
Owner

danielgtaylor commented Apr 25, 2024

@lsdch I'm not opposed to such a change if it can work. I'm willing to review and merge if you wanted to try it.

@davidolrik for healthz & readyz I would recommend just using the underlying router directly. These are usually internal implementation details of the service used by networking & cluster infrastructure like k8s to manage internal resources rather than being exposed publicly for clients to call. An added benefit of doing this is that it won't show up in the API docs which could be confusing to users. Something like (assuming Chi as the router):

type Checks struct {
  Live bool `json:"live"`
  DB bool `json:"db"`
}

type Ready struct {
  Ready bool `json:"ready"`
  Version string `json:"version"`
}

router.Get("/readyz", func(w http.ResponseWriter, r *http.Request) {
	ready := &Ready{
		// TODO: compute ready or not
	}

	b, err := json.Marshal(ready)
	// TODO: handle error

	if !ready.Ready {
		w.WriteHeader(http.StatusServiceUnavailable)
	}
	// If WriteHeader is never called it defaults to HTTP 200
	w.Write(b)
})

Part of the advantage of Huma is that sometimes it can get out of the way when you don't really need it 😁

@davidolrik
Copy link
Contributor

@danielgtaylor I see your point, but I like to document everything - and I find great value in being able to see which dependency that is currently broken, and often clients do too.

Guess what I really want, is a way to set the http response code for any response.

E.g. a POST endpoint that returns 201 when creating a resource, and 200 when updating it.

@danielgtaylor
Copy link
Owner

@davidolrik you can still document it manually by setting api.OpenAPI().Paths["/readyz"].Get.... If you don't want to manually write a JSON Schema you can also use api.OpenAPI().Components.Schemas.Schema(reflect.TypeOf(MyType{}), true, "hint").

Another alternative is to use a Status int field in your response struct, which will enable you to set 201 vs 200 etc. See https://huma.rocks/features/response-outputs/#status-code. Huma just won't know what values you might set in that field so it potentially requires a little manual documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants