how to consume http post in elm with header and body - elm

I am new in elm and try to consume web api using http post request with header and body using 0.17.1 version but did not get any documentation.
So any one help me to implement this functionality

The send method of the Http package gives you the possibility to create and send a custom request. For example, a post request could be something like
postRequest : Request
postRequest =
{ verb = "POST"
, headers =
[ ("Origin", "http://elm-lang.org")
, ("Access-Control-Request-Method", "POST")
, ("Access-Control-Request-Headers", "X-Custom-Header")
]
, url = "http://example.com/hats"
, body = empty
}
You can then create the Task that represent the request using the send function like
send defaultSettings postRequest

Related

How to automatically convert CSRF Tokens to HTTP request headers in Elm?

I am writing a single page application in Elm to interface with a Django backend. The Django Rest Framework provides a CSRF token in a cookie but expects all requests to contain the token in an HTTP header.
Is there a way to declaratively instruct Elm to return the CSRF token as HTTP header with each request? E.g., along the line how I would configure it in JS/Axios:
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
There is an old SO question that implies to manually extract the token from the cookie and then use Http.send for each request. That would mean to wrap all HTTP request functions by hand.
Using version 2.0.0 of the elm/http library, you would need to use request in order to provide headers. It's fairly common for an application to use a customized version of these "base" methods that ask for whatever your environment requires.
get httpConfig route tagger decoder =
Http.request
{ method = "GET"
, headers = httpConfig.headers
, url = httpConfig.baseUrl ++ route
, body = Http.emptyBody
, expect = Http.expectJson tagger decoder
, timeout = Nothing
, tracker = Nothing
}
post httpConfig route value tagger decoder =
Http.request
{ method = "POST"
, headers = httpConfig.headers
, url = httpConfig.baseUrl ++ route
, body = Http.stringBody "application/vnd.api+json" (Encode.encode 0 value)
, expect = Http.expectJson tagger decoder
, timeout = Nothing
, tracker = Nothing
}

Why does Telegram give me an empty POST request on the webhook?

I followed these steps:
Registered a bot with BotFather.
Send a post request for the webhook (https://api.telegram.org/bot[BOTID]/setWebhook) with the URL being https://example.com/myscript.php
Double check with getWebhookInfo and it showed it is correctly registered.
When I send a message to the bot, the script is being called but with an empty POST payload. In the documentation they say they would send an HTTPS POST request to the specified url, containing a JSON-serialized Update.
Does anyone else has this issue and perhaps know a way to resolve this?
My php script to log:
$file = dirname(__FILE__) . '/telegram-log.txt';
$entry = (object)array();
$entry->date = date("r");
$entry->GET = $_GET;
$entry->POST = $_POST;
$entry->REQUEST = $_REQUEST;
$entry->HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
$entry->REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
file_put_contents($file, json_encode($entry) . "\n", FILE_APPEND | LOCK_EX);
Response:
{"date":"Thu, 17 Jun 2021 13:42:49 +0200","GET":[],"POST":[],"REQUEST":[],"HTTP_USER_AGENT":null,"REMOTE_ADDR":"91.108.6.133"}
Use $content = file_get_contents("php://input") to receive updates.
Telegram's response is of content-type application/json.
$_POST will only work when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

Advice for implementing custom authentication scheme [duplicate]

First of all, thanks for build karate it's a very useful for test API's and UI's. We are using it to test a lot of our endpoints but we would like to know if there is a way or which is the best approach to handle requests with signature as part of the request in the header.
In our case we have two headers:
ApiKey: this value is always the same
Signature: this value depends on the request body content
Is there any way to inject the signature value just before the request is executed based on the request body content?
Here you can see two samples of the requests
Sample 1:
* url 'https://dev.sample.com'
* path '/api/user/getAll'
* header Content-Type = 'application/json'
* header ApiKey = 'XXX'
* header Signature = 'YYY'
And request { }
When method POST
Then status 200
Sample 2:
* url 'https://dev.sample.com'
* path '/api/user/getAll'
* header Content-Type = 'application/json'
* header ApiKey = 'XXX'
* header Signature = 'ZZZ'
And request { name: 'John' }
When method POST
Then status 200
Thanks
Karate has a "hook" for generating headers, but as of now it is not "aware" of the currently built request body + headers: https://github.com/intuit/karate#configure-headers
We got a similar request here, and are thinking of adding this capability: How to retrieve raw request contents before making a REST call in Karate DSL?
Maybe the OAuth examples will give you the way forward for your case for now: https://stackoverflow.com/a/55055111/143475
Feel free to raise an enhancement request, and we can get this in to the next version (with your help to test it). I'm thinking - what if you are able to call karate.get('request') from within the header JS function.
But for now all you need to do is do something like this:
* def body = { some: 'json' }
* karate.set('requestBody', body)
* url someUrl
* request body
* method post
And in the header.js function
function fn() {
var body = karate.get('requestBody');
var sign = Utils.sign(body);
return { Signature: sign };
}
EDIT: this will be implemented in Karate 1.0 onwards: https://github.com/intuit/karate/issues/1385

API Connect 5 - Error attempting to read the urlopen response data

I'm trying to create a REST API from a SOAP Service using IBM API Connect 5. I have followed all the steps described in this guide (https://www.ibm.com/support/knowledgecenter/en/SSFS6T/com.ibm.apic.apionprem.doc/tutorial_apionprem_expose_SOAP.html).
So, after dragging the web service block from palette, ensuring the correctness of endpoint and publishing the API, I have tried to call the API from the browser. Unfortunately, the API return the following message:
<errorResponse>
<httpCode>500</httpCode>
<httpMessage>Internal Server Error</httpMessage>
<moreInformation>Error attempting to read the urlopen response
data</moreInformation>
</errorResponse>
To testing purpose, I have logged the request and I have tried the request on SOAPUI. The service return the response correctly.
What is the problem?
In my case, the problem was in the backend charset (Content-Type: text/xml;charset=iso-8859-1).
For example, backend returns text/xml in German (or French). Api Connect cannot process character ΓΌ. It needs Content-Type: text/xml;charset=UTF-8.
I had a similar issue, in my case was the accept. if you have an Invoke and the content-type or the accept, is not matching the one of the request, or the response that you got, APIC is getting mad.
Please, check if the formats to send (contentType) and receive (accept) are the same of that your API expected. In my case the error occurs because the API returns a String and my default code is configured to receive a JSON body.
//define a JSON-PLAIN TEXT protocol
private HttpEntity<String> httpEntityWithBody(Object objToParse){
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "xxx token xxx");
headers.set("Accept", MediaType.TEXT_PLAIN_VALUE);
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new GsonBuilder().create();
String json = gson.toJson(objToParse);
HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
return httpEntity;
}
//calling the API to APIC...
ParameterizedTypeReference<String> responseType = new
ParameterizedTypeReference<String>(){};
ResponseEntity<String> result =
rest.exchange(builder.buildAndExpand(urlParams).toUri(), HttpMethod.PUT, httpEntityWithBody(myDTO), responseType);
String statusCode = result.getStatusCodeValue();
String message = result.getBody();

StrongLoop Loopback : How to customize HTTP response code and header

I'm looking for a way to customize StrongLoop LoopBack HTTP response code and headers.
I would like to conform to some company business rules regarding REST API.
Typical case is, for a model described in JSON, to have HTTP to respond to POST request with a code 201 + header Content-Location (instead of loopback's default response code 200 without Content-Location header).
Is it possible to do that using LoopBack ?
Unfortunately the way to do this is a little difficult because LoopBack does not easily have hooks to modify all responses coming out of the API. Instead, you will need to add some code to each model in a boot script which hooks in using the afterRemote method:
Inside /server/boot/ add a file (the name is not important):
module.exports = function(app) {
function modifyResponse(ctx, model, next) {
var status = ctx.res.statusCode;
if (status && status === 200) {
status = 201;
}
ctx.res.set('Content-Location', 'the internet');
ctx.res.status(status).end();
}
app.models.ModelOne.afterRemote('**', modifyResponse);
app.models.ModelTwo.afterRemote('**', modifyResponse);
};