ModelState validation, only shows one error at a time - asp.net-core-3.1

I have a WebAPI decorated with [ApiController] and have been testing the validation of the models. I noticed that they only return one validation error at a time, but in an array format. I purposely created several errors because I wanted to see the full report. So far all I have seen are a few questions with the same behaviour, but no answers.
Sample model:
public class MyModel {
[Range(0,12)]
public int MyInt { get; set; }
public DateTime MyDate { get; set; }
}
Sample JSON:
[
{
"MyInt": "textinanint",
"MyDate": "2020-09-29 5:00 PM"
}
]
Please note that date is not a valid JSON encoded date. There are two errors, but the validator will only return the first one like so:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|5fb75d1b-454a15260c502256.",
"errors": {
"$[0].myInt": [
"The JSON value could not be converted to System.Int32. Path: $[1].myInt| LineNumber: 2 | BytePositionInLine: 30."
]
}
}
I would except to see:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|5fb75d1b-454a15260c502256.",
"errors": {
"$[0].myInt": [
"The JSON value could not be converted to System.Int32. Path: $[0].myInt| LineNumber: 3 | BytePositionInLine: 30."
],
"$[0].myDate": [
"The JSON value could not be converted to System.DateTime. Path: $[0].myDate| LineNumber: 2 | BytePositionInLine: 22."
]
}
}
Is there a way to correct this behaviour? Forgive any issues with the json formatting in the expected output. I had to create it manually.

Related

GraphQL query result for object that does not exist

I have a GraphQL query that calls a REST service to get the return object. The query contains an Id parameter that is then passed to the service. However, the REST service can respond with http status 404 Not Found if an object with that Id does not exist. That seems like the right response.
How do you model a Not Found response in GraphQL?
Is there a way to inform the GQL caller that something does not exist?
Update
Some options I am considering:
Return null
Change the GrqlhQL Query to return a list of objects and return empty list of nothing is found
Return some kind of error object with an error code
but it is unclear if there is a recommended practice in GQL API design.
You might treat it as an error and handle it accordingly.
I recommend you to check the GraphQL spec, the paragraph about error handling.
I hope it contains exactly what you are looking for.
Basically, you should return whatever you could, and inform a client about potential problems in the "errors" field.
The example from the documentation:
Request:
{
hero(episode: $episode) {
name
heroFriends: friends {
id
name
}
}
}
Response:
{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ]
}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}
}

JSON timestamp wrong on FIWARE Orion Context Broker global instance

I am sending a POST request to http://orion.lab.fiware.org:1026/v2/entities/85/attrs?type=UrbansenseLocation in order to update atime and bundle attributes:
{
"atime":{
"type":"Number",
"value":1476370651},
"bundle":{
"type":"Number",
"value":1}
}
and a GET request to the same entity receives the following response:
{
"id": "85",
"type": "UrbansenseLocation",
"atime": {
"type": "Number",
"value": 1476370000,
"metadata": {}
},
"bundle": {
"type": "Number",
"value": 1,
"metadata": {}
},
//some other attributes
}
Please, note the mismatch on the value field of the atime attribute!!! Why is such thing happening?
Thanks.
I understand that atime is meant to be a datetime. In that case, I'd suggest to use the DateTime attribute type. This would provide a better semantic for the attribute and should avoid any number rending problem (as the ones that are being discussed right now at github).
More information about the DateTime type at the NGSIv2 specification (section "Special Attribute Types") and this document (look for the "Datetime support" slide).

Spring MVC - how to return different JSON responses based on query parameters?

I am implementing a REST api using Spring MVC. The requirement is:
/transactions returns an array of transactions.
/transactions?groupByCategory returns transactions grouped by categories.
For example request #1 returns:
[
{ "id": 1, "category": "auto", "amount": 100 },
{ "id": 2, "category": "misc", "amount": 200 },
{ "id": 3, "category": "auto", "amount": 300 }
]
whereas request #2 groups this result by category and returns the sum of each category:
[
{ "category": "auto", "amount": 400 },
{ "category": "misc", "amount": 200 }
]
Obviously the return value from these requests is of different types. How do I do this in Spring MVC? So far I have:
#RequestMapping("/transactions")
public List<Transaction> getTransactions(
#RequestParam(value="groupByCategory", required=false) String groupByCategory
) {
...
}
But this fixes the return type to List<Transaction>. How do I accommodate the second type: List<TransactionSummaryByCategory>?
Edit: I found one solution, i.e. to specify the return type as Object. That seems to work and the response is serialized correctly based on the object type. However, I wonder if this is a best practice!
public Object getTransactions(...) {
...
}
You can simply provide two methods in your controller. First one returning List<Transaction> mapped using
#RequestMapping("/transactions")
and the second one returning List<TransactionSummaryByCategory> and mapped using
#RequestMapping(value = "/transactions", params = "groupByCategory")
You can return a generic List.
public List<?> getTransactions()
{
}
Based on the request params you can populate the list with the appropriate objects

Office365/Sharepoint:: API Error when getting ParentUniqueId for a list item

I'm trying to identify the Parent Id for a list item.
I'm making the following call;
https://{sitecollection}/{personal_site}/_api/Web/Lists(guid'blabla')/Items(blabla)?$select=ParentUniqueId
But it is giving me the following error;
{
"error": {
"code": "-1, Microsoft.SharePoint.SPException",
"message": {
"lang": "en-US",
"value": "The field or property 'ParentUniqueId' does not exist."
}
}
}
The same issue is with "ParentLeafName" and some others.
However, when I get the /fields (meta of fields for a list) for this list, it mentions this field along with others, which means I'm doing the right call as I'm successfully getting other fields like
https://{sitecollection}/{personal_site}/_api/Web/Lists(guid'blabla')/Items(blabla)?$select=ServerUrl
Result
{
"d": {
"__metadata": {
"id": "blabla",
"uri": "blabla",
"etag": "\"10\"",
"type": "SP.Data.DocumentsItem"
},
"ServerUrl": "/personal/{site}/{filepath}"
}
}
One thing I have noticed though, that these fields are case sensitive, that is, if i write "serverurl" it gives me the same error. Is this a case issue with "ParentUniqueId" field?
Unfortunately ListItem resource in SharePoint 2013 REST interface does not expose ParentUniqueId property.
But you could use the following query to return ParentUniqueId property for ListItem:
/_api/Web/Lists/getByTitle('<list title>')/items(<item id>)/FieldValuesAsText?$select=ParentUniqueId
References
Lists and list items REST API reference

GoodData "Create Report Definition" API Call giving 500 Internal Server Error

I'm trying to create a report definition using the GoodData REST API. I use the following endpoint to invoke the rest call.
"/gdc/md/{project-id}/obj"
When i try to invoke the API call with the following dataset in which the projectId and the userId are valid, it gives me the error with the response code 500.
{
"reportDefinition": {
"content": {
"filters": [],
"format": "grid",
"grid": {
"rows": [],
"columns": [
"metricGroup"
],
"sort": {
"columns": [],
"rows": []
},
"columnWidths": [],
"metrics": [
{
"uri": "/gdc/md/qy48iv4flikdlcwpwioizuip74wt8nb5/obj/63f3cecd2a8d3ce2ec9378381c8f39e3",
"alias": ""
}
]
}
},
"meta": {
"title": "Sample report definition",
"summary": "This is a sample report",
"tags": "",
"deprecated": 0,
"category": "samplecategory"
}
}
}
{
"error": {
"message": "Internal server error. Please fill in bug report with request_id='lp78FL5S1IPMqB2n'"
}
}
I'm certain that the user project_id and the user_id are valid. Is this an error in the API?
Thank you in advance.
Apart from the metrics URI that looks weird (hash instead of numeric ID), I was able to dig in our logs an error that says: "Category is not equal to tag structure".
In your example you have its value set to "samplecategory". "category" property defines what type of object are you creating. If you are creating a report definition it should have value of "reportDefinition".
Last time I worked with GoodData API, metrics had numeric IDs. That seems most likely to be the culprit. Where did you get "/gdc/md/qy48iv4flikdlcwpwioizuip74wt8nb5/obj/63f3cecd2a8d3ce2ec9378381c8f39e3" from, especially the "63f3cecd2a8d3ce2ec9378381c8f39e3" part?