Alamofire.upload with query parameters - alamofire

I'm using Alamofire.upload to upload an image as a .POST multipart to my server. But my server always gets parameters only as a query string, and use multipart only for a file data. So in my request I also need to put some parameters to URL, but it seems Alamofire.upload have't a variant with parameters argument.
Alamofire.upload(
.POST,
"https://httpbin.org/post?user=\(userId)&photo=\(photoTitle)",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
},
encodingCompletion: nil
)
For now I just put all parameters by myself directly forming request-string: "https://httpbin.org/post?user=\(userId)&photo=\(photoTitle)".
Is there a better way to pass query parameters to Alamofire.upload?

What can do things better is Alamofire.ParameterEncoding, but it will need some workaround with requests.
var req: NSMutableURLRequest?
(req!, _) = Alamofire.ParameterEncoding.URL.encode(
NSURLRequest(URL: NSURL(string: "https://httpbin.org")!),
parameters: ["user": userId, "photo": photoTitle]
)
Alamofire.upload(
.POST,
req!.URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
},
encodingCompletion: nil
)

Related

How to use gt/le operator in aurelia slickgrid with Odata

I want to send my own operator in odata request and not use the aurelia slickgrid inbuilt "eq" operator.
This is my column definition
{
id: 'LockoutEndDateUtc', name: 'Status', field: 'LockoutEndDateUtc', minWidth: 85, maxWidth: 95,
type: FieldType.boolean,
sortable: true,
formatter: Formatters.multiple,
params: { formatters: [this.StatusFormatter, Formatters.checkmark] },
filterable: true,
filter: {
collection: [
{ value: 'le ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'True' },
{ value: 'gt ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'False' }
], //['', 'True', 'False'],
model: Filters.singleSelect,//multipleSelect//singleSelect,
}
}
This is the UI
This is how the request filter looks like..
$filter=(LockoutEndDateUtc%20eq%20le%202022-06-28T12%3A59%3A25Z)
If i remove %20eq from the above request, everything else works. So my question is how to i remove %20eq. Or how do i send my own gt, le in the request.
You can't really do that on a boolean filter (you could however do it on a date filter with operator) and I don't think I've added any ways to provide a custom filter search the way you want to do it, but since you're using OData, you have a bit more control and you could change the query string yourself. To be clear, it's not at all recommended to change the OData query string, it's a last solution trick and at your own risk, but for your use case it might be the only way to achieve what you want.
prepareGrid() {
this.gridOptions = {
// ...
backendServiceApi: {
service: new GridOdataService(),
process: (query) => this.getCustomerApiCall(query),
} as OdataServiceApi
};
}
}
getCustomerApiCall(query: string) {
let finalQuery = query;
// in your case, find the boolean value from the column and modify query
// your logic to modify the query string
// untested code, but it would probably look similar
if (query.includes('LockoutEndDateUtc%20eq%20true')) {
// calculate new date and replace boolean with new date
finalQuery = query.replace('LockoutEndDateUtc%20eq%20true', 'LockoutEndDateUtc%20le%202022-06-28T12%3A59%3A25Z');
}
return finalQuery;
}
Another possible solution but requires a bit more work.
If I'd be using a regular grid, without backend service and without access to the query string, I would probably add an external drop down outside of the grid and also add the date column and then control filters in the grid by using dynamic filtering. You can see a demo at Example 23, the principle is that you keep the column's real nature (date in your case) and filter it, if you want something like a "below today's date" then add an external way of filtering dynamically (a button or a drop down) and control the filter dynamically as shown below (from Example 23)

Google App Script Big Query - GoogleJsonResponseException: API call to bigquery.jobs.query failed with error: Query parameter 'X' not found

I have been struggling with this for a couple of days now and I felt like I should reach out. This might be very simple but I am not from a programming background and I haven't found any resources to solve this so far.
Basically, I want to parameterize a SQL query that is running for BigQuery within Google APp Script, it takes a variable from a user from a Google From they have submitted and I wanted to ensure that this won't be injectable by parameterizing the query, however, I got the following error that I could not fix:
GoogleJsonResponseException: API call to bigquery.jobs.query failed with error: Query parameter 'account_name' not found at [1:90]
Here is how I run the query:
//Query
const sqlQuery = 'SELECT district FROM `table` WHERE account_name = #account_name AND ent_theatre=("X") LIMIT 1;'
const request = {
query: sqlQuery,
params: { account_name: queryvar },
useLegacySql: false,
};
// Run Query
var queryResult = BigQuery.Jobs.query(request,projectID);
I have created the query based on Google's documentation
Your syntax for request object is not correct. The right syntax for the BigQuery.Jobs.query Request is like below:
const request = {
query: sqlQuery,
queryParameters: [
{
name: "account_name",
parameterType: { type: "STRING" },
parameterValue: { value: queryvar }
}
],
useLegacySql: false,
};
For more detail about QueryRequest Object refer to this link.

How to construct Parse Objects from JSONs?

I have JSONs like this;
{
createdAt: a_date,
text: "some text",
likes: 8
}
And I want to convert them into PFObjects… here’s how I do it;
let post = PFObject(className: "Post", dictionary: jsonPost)
The thing is that after that, the PFObject doesn’t have a value at its createdAt property.
post.createdAt <== this is always nil
I did some digging and tried this, but still no success;
jsonPost["_created_at"] = ["__type": "Date", "iso": "2020-09-23T13:31:08.877Z"]
Any idea why?
I think you might need to manually assign each param:
let postJson = {
createdAt: a_date,
text: "some text",
likes: 8
};
// create the Parse Object with Class 'Post'
let post = Parse.Object.extend('Post');
// assign param
post.set('text', postJson.text)
post.set('likes',postJson.likes)
post.save().then()...
createdAt is automatically handled by Parse Server when you save an object. If you want to manually control it with your own timestamp, then you will need to add a field:
post.set('myCreatedAt',postJson.createdAt)

JWS Error during API testing python flask

I am trying to test a function, which basically calls the API by passing a some values, which is then loaded to the schema to be validated and then accepted or rejected based on validation.
The below is my test function.
params = {
'first': [10,20],
'second': 400,
'third ': 'Testing'
}
headers = {
'Authorization': 'Bearer{}'.format(token),
'Data-type' : "json"
}
response = self.client.post(url_for('MyView:post', id=current_id.id),
json=params,
headers=headers)
This renders me the error below:
{
"msg": "Invalid header string: must be a json object"
}
I was able to check the issue and found out its due to the mapping of invalid types. But as headers is still a dictionary, I am not able to comprehend why this error is being rendered.
I have also added the structure of my schema and API below:
class MySchema(marshmallow.Schema):
id = fields.Integer(required=True)
second = fields.Integer(fields.Integer(), required=True)
first = fields.List(fields.String(), required=False)
third = fields.Str(validate=validate.Length(min=0, max=255), required=False)
class Meta:
fields = ('id',
'second',
'first',
'third')
#validates_schema(pass_original=True)
def validate_numbers(self, _, data):
//function code
The below is the structure of my API
class MyView(V1FlaskView):
#jwt_requried
def post(id):
//code
Maybe a space character is missing after Bearer:
'Authorization': 'Bearer {}'.format(token),

Keen-io: i can't delete special event using extraction query filter

using extraction query (which used url decoded for reading):
https://api.keen.io/3.0/projects/xxx/queries/extraction?api_key=xxxx&event_collection=dispatched-orders&filters=[{"property_name":"features.tradeId","operator":"eq","property_value":8581}]&timezone=28800
return
{
result: [
{
mobile: "13185716746",
keen : {
timestamp: "2015-02-10T07:10:07.816Z",
created_at: "2015-02-10T07:10:08.725Z",
id: "54d9aed03bc6964a7d311f9e"
},
data : {
itemId: 2130,
num: 1
},
features: {
communityId: 2000,
dispatcherId: 39,
tradeId: 8581
}
}
]
}
but if i use the same filters in my delete query url (which used url decoded for reading):
https://api.keen.io/3.0/projects/xxxxx/events/dispatched-orders?api_key=xxxxxx&filters=[{"property_name":"features.tradeId","operator":"eq","property_value":8581}]&timezone=28800
return
{
properties: {
data.num: "num",
keen.created_at: "datetime",
mobile: "string",
keen.id: "string",
features.communityId: "num",
features.dispatcherId: "num",
keen.timestamp: "datetime",
features.tradeId: "num",
data.itemId: "num"
}
}
plz help me ...
It looks like you are issuing a GET request for the delete comment. If you perform a GET on a collection you get back the schema that Keen has inferred for that collection.
You'll want to issue the above as a DELETE request. Here's the cURL command to do that:
curl -X DELETE "https://api.keen.io/3.0/projects/xxxxx/events/dispatched-orders?api_key=xxxxxx&filters=[{"property_name":"features.tradeId","operator":"eq","property_value":8581}]&timezone=28800"
Note that you'll probably need to URL encode that JSON as you mentioned in your above post!