atc-net/atc-rest-api-generator

Validation fails to detect missing array that is marked as required

cjakobsen opened this issue · 0 comments

Describe the bug
Marking an array as required produces code that will not return a validation error if the array is omitted in a POST/PUT request.

To Reproduce
Steps to reproduce the behavior:

  1. Run the Demo Api project included in the sample
  2. POST to the /items endpoint to create an item, use this json as body:
{
  "item": 
  {
      "name" : "test"
  }
}
  1. An error is returned but that is because the operation is not implemented

Expected behavior
A validation error should be returned telling that the array MyItems is required.

Screenshots
Response from original code:

{
  "title": "Not Implemented",
  "status": 501,
  "detail": "TraceId: D54262BB-C0E6-40ED-B26B-5287FB051866 # NotImplemented: The method or operation is not implemented."
}

Suggested fix
The problem is caused by the generated code shown below. MyItems property is assigned a default value new List and this will cause the validation to think that the array is present in the case where it is actually not.

  [GeneratedCode("ApiGenerator", "1.1.15.0")]
  public class CreateItemRequest
  {
      /// <summary>
      /// Item.
      /// </summary>
      [Required]
      public Item Item { get; set; }

      [Required]
      public List<Item> MyItems { get; set; } = new List<Item>();

      /// <summary>
      /// Converts to string.
      /// </summary>
      public override string ToString()
      {
          return $"{nameof(Item)}: ({Item}), {nameof(MyItems)}: {MyItems}";
      }
  }

Removing the default value for MyItems will solve the problem. Response when this is removed:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-7f6542e82278a945bd0749552622c81d-79c96fe367f21041-00",
  "errors": {
    "Request.MyItems": [
      "The MyItems field is required."
    ]
  }
}