Flask-Restful: can't parse args of json nested value - flask-restful

I've got the json
{
"message": {
"foo": "foo",
"bar": "bar"
}
}
And parser:
parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('foo', type=str, required=True)
parser.add_argument('bar', type=str, required=True)
args = parser.parse_args()
And the error is :
{'foo': 'Missing required parameter in the JSON body or the post body or the query string', 'bar': 'Missing required parameter in the JSON body or the post body or the query string'}

Since your 'foo' and 'bar' keys are inside 'message', the JSON parsing has to start from 'message'.
ie. You have to let know the parser about 'message' before you can parse 'foo' from it.
For this, you have to set up a root parser which parses your 'message'. You can do this in the following way:
root_parser = reqparse.RequestParser()
root_parser.add_argument('message', type=dict)
root_args = root_parser.parse_args()
message_parser = reqparse.RequestParser()
message_parser.add_argument('foo', type=dict, location=('message',))
message_parser = message_parser.parse_args(req=root_args)
For more info please take a look at the issue from github

Related

Using FastAPI & Pydantic, how do I define an Optional field with a description

For a FastAPI Pydanctic class I have these values
class ErrorReportRequest(BaseModel):
sender: Optional[str] = Field(..., description="Who sends the error message.")
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
I use the class as an input model
router = APIRouter()
#router.post(
"/error_report",
response_model=None,
include_in_schema=True,
)
def error_report(err: ErrorReportRequest):
pass
When I run this, sender is a required field. If it's not included in the incoming JSON, I get a validation error.
Input:
{
"error_message_displayed_to_client": "string"
}
Results in:
{
"detail": [
{
"loc": [
"body",
"sender"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
If I remove the Field description like this:
class ErrorReportRequest(BaseModel):
sender: Optional[str]
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
the request passes.
How can I add a Field description to an optional field so that it's still allowed to omit the field name?
You'll need to provide an explicit default value to Field, for example None instead of ...:
class ErrorReportRequest(BaseModel):
sender: Optional[str] = Field(None, description="Who sends the error message.")
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
... indicates that the value is required. This is of course in conflict with the Optional, but it looks like pydantic gives higher priority to ....
From the documentation of Field:
default: (a positional argument) the default value of the field. Since the Field replaces the field's default, this first argument can be used to set the default. Use ellipsis (...) to indicate the field is required.

Mirage Passthrough returns Response Object instead of JSON data returned from network call

I am getting an error:
Mirage: Your Ember app tried to GET 'http://localhost:3006/data.json',
but there was no route defined to handle this request.
Define a route that matches this path in your mirage/config.js file.
Did you forget to add your namespace?
So following the documentation of mirage i added this:
this.passthrough('http://localhost:3006/data.json');
Even though after adding passthrough, I am getting such Response instead of JSON Object returned from the network api call.
The Actual Request i am making is:
fetch(`${host}/data.json`)
.then(res => res.json())
.then(data => {
// my operation on data
});
The response i am getting is:
{bodyUsed: true
headers: Headers {map: {…}}
ok: true
status: 200
statusText: "OK"
type: "default"
url: "http://localhost:3006/data.json"
_bodyInit: null
_bodyText: ""}
But I am expecting:
{
"files":
{
"x": "any",
"a": "any",
"b": "any",
"c": "any"
}
}
I kept a debugger in Pretender.js which is sending the FakeRequest and there in its object, I see that FakeRequest has responseType="" and response as null. And somehow my responseText has value but that is not considered and response value is considered and receiving null.
Also there is a logic which is return saying
"response" in xhr ? xhr.response : xhr.responseText
In this case i have response property but its value is null. Hence according to the above condition it is returning xhr.response which is null
Thanks in Advance.

AWS AppSync - DeleteItem doesn't execute response mapping template

When attempting to delete an item using the following request mapping:
{
"version" : "2017-02-28",
"operation" : "DeleteItem",
"key" : {
"id": { "S" : "$ctx.args.id"},
"sortKey" : { "S" : "$ctx.args.sortKey"}
}
}
If the item exists it will process the result through the response template, however when the item does not exist the response template is never run.
Response template:
#set($ctx.result.status = "SUCCESS")
#set($ctx.result.message = "This was a success!")
$utils.toJson($ctx.result)
I am aware that when an item does not exist in Dynamo it will perform no action but I would expect that it would still process through the template.
Is there anything I am missing or is it impossible for AppSync to processed a DeleteItem request through the response mapping when the document does not exist?
This the expected execution behavior for the version of the template you are using (2017-02-28).
You can switch your request mapping template version to 2018-05-29 and your response mapping template will be executed, with the following characteristics:
If the datasource invocation result is null, the response mapping template is executed.
If the datasource invocation yields an error, it is now up to you to handle the error. The invocation error is accessible using $ctx.error.
The response mapping template evaluated result will always be placed inside the GraphQL response data block. You can also raise or append an error using $util.error() and $util.appendError() respectively.
More info https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-changelog.html#aws-appsync-resolver-mapping-template-version-2018-05-29
So for your example:
{
"version" : "2018-05-29", ## Note the new version
"operation" : "DeleteItem",
"key" : {
"id": { "S" : "$ctx.args.id"},
"sortKey" : { "S" : "$ctx.args.sortKey"}
}
}
and response template
#if ( $ctx.error )
$util.error($ctx.error.message, $ctx.error.type)
#end
#set($ctx.result.status = "SUCCESS")
#set($ctx.result.message = "This was a success!")
$utils.toJson($ctx.result)

checking partcular filed in a response in spring cloud contact creation

Is there any way to test only particular field in a response is matching with the given text or not while writing a contract using spring-cloud-contract framework.
package contracts
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'GET'
url value(consumer(regex('/app/emp/employee/[0-9]{3}')), producer('/app/emp/employee/151'))
}
response {
status 200
body([
subjectsList: null,
errorResponse: null,
status: 'success',
employeeList: null,
Employee: [
EmployeeId: 151,
firstName: 'xxx',
lastName: 'xxx',
middleName: 'xxx',
dateOfBirth: 01012001,
status: 'inbound',
cin: '345',
ssn: null,
EmployeeType: 'HoH',
preferredLanguage: 'french',
preferredContactMethod: null,
createdBy: null,
creadtedOn: null,
updatedBy: null,
updatedOn: null,
transactionId: null
],
paginated: null
])
headers {
header('Content-Type': value(
producer(regex('application/json.*')),
Employee('application/json')
))
}
}
}
Instead of writing complete response, Is there any way to check only particular attribute present in the response for ex: language = 'french'
Thanks in advance, your help is very much appreciated.
Sure, just remove all the other fields. Whatever you put in the body will get asserted. BTW what you do with the contract looks like a schema. If a field is null that means that it has to be there and it has to be null or rather it's optional?
If you want to do any custom assertion on the part of / whole body you can use this http://cloud.spring.io/spring-cloud-static/Dalston.SR4/multi/multi__contract_dsl.html#_dynamic_properties_in_matchers_sections and pass any jsonpath element for custom assertion
BTW for the response you can write headers { contentType(applicationJson()) }

Polymer 1.x: $key throws error when saving to Firebase

I want to save a firebase-document to Firebase. But I encounter the following error.
error.log
Uncaught (in promise) Error: Firebase.push failed: first argument contains an invalid key ($key) in property 'xxxxxxxxxxxx.items'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"
Here is the relevant code.
my-element.html
<firebase-document id="document" ... ></firebase document>
...
save: function() {
var doc = this.$.document;
console.log('Saved', doc.data);
return doc.save(this.itemsPath).then(function() {
console.log('Saved:', doc);
doc.reset();
}.bind(this));
return Promise.resolve();
},
The data object contains a key label containing the $ character. But this is automatically introduced by Firebase, not a programming decision.
console.log
Saved: {
$key: "foo" // This is the object key in Firebase
...
}
What edits can I make to save my data?

Resources