huma icon indicating copy to clipboard operation
huma copied to clipboard

Feature request: strict validation for query parameters

Open baderj opened this issue 1 year ago • 1 comments

According to the documentation Huma is strict about unexpected fields:

By default, Huma is strict about which fields are allowed in an object, making use of the additionalProperties: false JSON Schema setting. This means if a client sends a field that is not defined in the schema, the request will be rejected with an error. This can help to prevent typos and other issues and is recommended for most APIs.

However, this does not currently apply to query parameters. Any additional query parameters are silently discarded. For example, here is the example from the tutorial where I changed name to be a query parameter:

package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humachi"
	"github.com/go-chi/chi/v5"

	_ "github.com/danielgtaylor/huma/v2/formats/cbor"
)

// GreetingOutput represents the greeting operation response.
type GreetingOutput struct {
	Body struct {
		Message string `json:"message" example:"Hello, world!" doc:"Greeting message"`
	}
}

func main() {
	// Create a new router & API
	router := chi.NewMux()
	api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))

	// Register GET /greeting/{name} handler.
	huma.Get(api, "/greeting", func(ctx context.Context, input *struct {
		Name string `query:"name" maxLength:"30" example:"world" doc:"Name to greet"`
	}) (*GreetingOutput, error) {
		resp := &GreetingOutput{}
		resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
		return resp, nil
	})

	// Start the server!
	http.ListenAndServe("127.0.0.1:8888", router)
}

If the API is requested with a misspelled query parameter (firstname instead of name), then no error is returned:

restish :8888/greeting\?firstname=world
HTTP/1.1 200 OK
Content-Length: 81
Content-Type: application/cbor
Date: Wed, 27 Nov 2024 08:58:42 GMT
Link: </schemas/GreetingOutputBody.json>; rel="describedBy"

{
  $schema: "http://localhost:8888/schemas/GreetingOutputBody.json"
  message: "Hello, !"
}

It would be nice to have the option to be strict about unexpected query parameters and return an error in these cases.

baderj avatar Nov 27 '24 09:11 baderj