I'm trying to send a notification from flutter application directly, but I can not figure it out how to do it.
Everywhere they say have to send a curl request with basic network library but there is no example.
DATA='{"notification": {"body": "this is a body","title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "<FCM TOKEN>"}'
curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=<FCM SERVER KEY>"
Please help me with an example in DART.
You could try this:
import 'dart:async';
import 'dart:convert' show Encoding, json;
import 'package:http/http.dart' as http;
class PostCall {
final postUrl = 'https://fcm.googleapis.com/fcm/send';
final data = {
"notification": {"body": "this is a body", "title": "this is a title"},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done"
},
"to": "<FCM TOKEN>"
};
Future<bool> makeCall() async {
final headers = {
'content-type': 'application/json',
'Authorization': 'key=<FCM SERVER KEY>'
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
// on success do sth
return true;
} else {
// on failure do sth
return false;
}
}
}
Related
Have anyone tried to run Automation Anywhere A360 import API with HTTP Post action with Power Automate Flow?
The flow runs smoothly and I'm receiving the requestId in response. However, the whole action fails at the Automation Anywhere Control Room side with no imported bot at the end. I'm receiving the following error: net.lingala.zip4j.exception.ZipException: Zip headers not found. Probably not a zip file?
Power Automate HTTP Post - Body
I added below code to the Http Post Body:
{
"$content-type": "multipart/form-data",
"$multipart": [
{
"headers": {
"Content-Type": "application/x-zip-compressed",
"Content-Disposition": "form-data; name=\"upload\"; filename=\"#{variables('fullPath')}\""
},
"body": "#{variables('contentString')}"
},
{
"headers": {
"Content-Disposition": "form-data; name=\"actionIfExisting\""
},
"body": "OVERWRITE"
},
{
"headers": {
"Content-Disposition": "form-data; name=\"publicWorkspace\""
},
"body": "true"
},
{
"headers": {
"Content-Disposition": "form-data; name=\"upload\""
},
"body": "#{variables('fullPath')}"
}
]
}
The contentString variable is: #{body('Get_file_content_using_path')?['$content']}
What am I doing wrong?
I use React Native fetch to POST to endpoint which is AWS Lambda. By default it's HTTP/2. That works perfectly fine with curl:
% curl -X POST https://yyyyyy.execute-api.eu-central-1.amazonaws.com/Test/stripe_payment -H "x-api-key: xxxxx"
% {"errorCode": "OK", "client_secret": "zzzz"}
But the same from react native:
try {
response = await fetch(`${API_URL}/stripe_payment`, {
method: 'POST',
headers: {
'x-api-key': API_KEY,
},
});
}
catch (error) {
console.error(error);
}
console.log('API response', response);
Returns only Lambda headers, not body:
API response {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "dce744f2-6755-47e0-9a9d-74921ae64eba", "offset": 0, "size": 100}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "dce744f2-6755-47e0-9a9d-74921ae64eba", "offset": 0, "size": 100}}, "bodyUsed": false, "headers": {"map": {"content-length": "100", "content-type": "application/json", "date": "Fri, 11 Nov 2022 19:33:22 GMT", "x-amz-apigw-id": "bc58SFhsFiAFp1A=", "x-amzn-requestid": "fc157dbb-72d2-459e-a391-1ece0ff9680f", "x-amzn-trace-id": "Root=1-636ea381-0c40c8ec31bb9c4f52d0e44b;Sampled=0"}}, "ok": true, "status": 200, "statusText": "", "type": "default", "url": "https://yyyyyy.execute-api.eu-central-1.amazonaws.com/Test/stripe_payment"}
Above response is correct, but it contains only headers, no body.
I do suspect that is because of HTTP/2 binary protocol, looking at some discussions looks like react native did not support it correctly in the past.
Any hints ?
Thanks,
Mark
ok, looks like i have found the answer: https://github.com/facebook/react-native/issues/24520
I am working on wiremock POC and I am facing issues when I try to send an attribute from request payload in response payload.
Request Payload:
{
"work_order": "12345678"
}
Mapping file:
{
"request": {
"method": "POST",
"urlPath": "/transform"
},
"response": {
"status": 200,
"body": "{\"randomInteger\": \"{{randomValue type = 'UUID'}}\",\"CorrelationID\": \"{{{request.body}}}\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}
Response Payload:
{
"randomInteger": "d24ea3bf-36c0-40b8-b84b-b9268ee85f55",
"CorrelationID": "{
"work_order": "12345678"
}"
}
Above is working fine.
Now if I try to select the attribute value instead of entire body file, it is not working.
Mapping File:
{
"request": {
"method": "POST",
"urlPath": "/transform"
},
"response": {
"status": 200,
"body": "{\"randomInteger\": \"{{randomValue type = 'UUID'}}\",\"CorrelationID\": \"{{{request.body.work_order}}}\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}
Response Payload:
{"randomInteger": "e35e4d5f-b043-4770-b659-4131d313e002","CorrelationID": ""}
Using .NET Core 3.1 and Microsoft.AspNetCore.OData 8.0.4.
I've set up Batch on my API and it works if all the requests in the batch are GET.
But if I put any updates, it fails with an error I can't figure out.
Successful direct update:
curl --location --request PATCH 'https://localhost:44390/api/odata/TradeTypeSpread(8432C89B-6D71-48B2-9F40-0000190AD326)' \
--header 'ApiAccessKey: xxxx' \
--header 'Content-Type: application/json' \
--data-raw '{
"Id":"8432C89B-6D71-48B2-9F40-0000190AD326",
"Spread": 3.0
}'
200 OK
{
"error": null,
"isSucceeded": true,
"id": null
}
Failed batch update:
curl --location --request POST 'https://localhost:44390/api/Odata/$batch' \
--header 'ApiAccessKey: xxx' \
--header 'Content-Type: application/json' \
--data-raw '{
"requests": [
{
"id": "1",
"method": "PATCH",
"url": "/api/odata/TradeTypeSpread(8432C89B-6D71-48B2-9F40-0000190AD326)",
"body": {
"Id": "8432C89B-6D71-48B2-9F40-0000190AD326",
"Spread": 3.0
}
}
]
}'
{
"responses": [
{
"id": "1",
"status": 400,
"headers": {
"content-type": "application/json; odata.metadata=minimal; odata.streaming=true",
"odata-version": "4.0"
},
"body": {
"error": {
"code": "",
"message": "The input was not valid.",
"details": [
{
"code": "",
"message": "The input was not valid."
}
]
}
}
}
]
}
Can anyone see what I'm doing wrong in the second sample?
Startup Code:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var defaultODataBatchHandler = new DefaultODataBatchHandler();
defaultODataBatchHandler.MessageQuotas.MaxNestingDepth = 2;
defaultODataBatchHandler.MessageQuotas.MaxOperationsPerChangeset = 100;
services
.AddControllersWithViews(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
options.Filters.Add(typeof(ValidateModelStateAttribute));
})
.AddNewtonsoftJson(options => options.SerializerSettings.UseDefaultSettings(nullValueHandling: Newtonsoft.Json.NullValueHandling.Include))
.AddOData(opt => opt.AddRouteComponents(
"api/odata",
new ModuleOdataEntityDataModel().GetEntityDataModel(),
defaultODataBatchHandler)
.Select().Filter().Count().OrderBy().Expand().SetMaxTop(Convert.ToInt32(Configuration["OdataMaxPageSize"])))
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
Controller Code
public class TradeTypeSpreadController : ODataController
{
[EnableQuery]
public async Task<IQueryable<TradeTypeSpreadDto>> Get()
{
...
}
public async Task<IActionResult> Patch(Guid key, Delta<TradeTypeSpreadDto> detalTradeSpreadDto)
{
...
}
}
Thanks
Sam
Working batch update for OData in ASP Net Core might look like this:
[AcceptVerbs("PATCH", "MERGE")]
public async Task<IActionResult> Patch(
[FromODataUri] string key,
Delta<MyModel> patch)
{
var model = patch.GetInstance();
await _repository.Update(model);
// IQueryable
var res = _repository.GetAll().SingleOrDefault(x => x.Id == key);
return Updated(res);
}
And it expects "get single" to be available as well:
[EnableQuery]
public IActionResult Get(
[FromODataUri] string key)
{
var dataset = _salesAreaBandsRepository.GetAll();
return Ok(dataset.SingleOrDefault(x => x.Id == key));
}
And of course the GetEdmModel() has to be adjusted if you use compound key or other field as a key:
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var entitySet1 = builder.EntitySet<MyModel>("MyModel");
entitySet1.EntityType.HasKey(entity => entity.OtherKey);
return builder.GetEdmModel();
}
And you have:
app.UseODataBatching();
Sometimes you also need to change AddRouteComponents:
AddRouteComponents("odata", GetEdmModel(),
new DefaultODataBatchHandler())
Im trying to make this api POST request to view.publish endpoint on slack api
As the documentation explains, im using the token and user_id in params, but i dont know what do i need to do with the view param
i set "application/json;charset=UTF-8" as content-type in the headers and on the body the JSON of the payload i want to publish:
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "This is a section block with a button."
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Me",
"emoji": true
},
"value": "click_me_123",
"url": "http://scoreboard-azureslackbot-salvosoftware.s3-website.us-east-2.amazonaws.com/",
"action_id": "button-action"
}
}
]
}
This error is displayed when i make that api call:
{
"ok": false,
"error": "invalid_arguments",
"response_metadata": {
"messages": [
"[ERROR] failed to match all allowed schemas [json-pointer:/view]",
"[ERROR] must provide an object [json-pointer:/view]",
"[ERROR] must provide an object [json-pointer:/view]"
]
}
}
Documentation says that view must be a JSON-encoded string
Also this warning is displayed in the body tab:
This answer is from Aubrey, support team in slack.
No params needed.
In the Authorization tab you need beared authorization.
On the body you need to set is as raw -> JSON and this would be your JSON:
{
"user_id": {{YOUR_USER_ID}},
"view": {
"type": "home",
"blocks": [
{
{{YOUR_PAYLOAD}}
}
]
}
}
It helped me basing on this CURL command
curl -L -X POST 'https://slack.com/api/views.publish' \
-H 'Content-type: application/json' \
-H 'Authorization: Bearer {{YOUR TOKEN}}' \
--data-raw '{
"user_id": {{YOUR USER ID}},
"view": {
"type": "home",
"blocks": [{
{{YOUR PAYLOAD}}
}]
}
}'