I need to make request like this Postman one, but in Alamofire
curl -X DELETE \
http://someUrl \
-H 'authorization: JWT someToken' \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-H 'postman-token: 0149ef1e-5d45-34ce-3344-4b658f01bd64' \
-d id=someId
I guess it should be something like:
let headers = ["Content-Type": "application/x-www-form-urlencoded", "Authorization": "JWT someToken"]
let params: [String: Any] = ["id": "someId"]
Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers).validate().responseJSON { responseJSON in
switch responseJSON.result {
case .success( _):
let data = responseJSON.result.value!
print(data)
case .failure(let error):
print(error.localizedDescription)
}
}
How can I check that my request has option like this from cUrl - -d id=someId
You do this:
Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers).validate().responseJSON { ... }
In fact, it can be deconstruct like that:
let request = Alamofire.request("http://someUrl", method: .delete, parameters: params, headers: headers)
request.validate().responseJSON { ... }
request is a DataRequest, which inherits from Request which has a pretty override of debugDescription that calls curlRepresentation().
If you print request, you'll have:
$> CredStore - performQuery - Error copying matching creds. Error=-25300, query={
atyp = http;
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = http;
"r_Attributes" = 1;
sdmn = someUrl;
srvr = someUrl;
sync = syna;
}
$ curl -v \
-X DELETE \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 11.4.0) Alamofire/4.7.3" \
-H "Accept-Language: en;q=1.0, fr-FR;q=0.9" \
"http://someUrl?id=someId"
Pretty cool, right? But no -d option. You can even check it with print(request.request.httpBody) and get:
$> nil
To fix it, use the encoding (ParameterEncoding) parameter in the init. You can use by default JSONEncoding, URLEncoding and PropertyListEncoding.
But you want to put the parameter in the httpBody, so use URLEncoding(destination: .httpBody):
Alamofire.request("http://someUrl", method: .delete, parameters: params, encoding: URLEncoding(destination: .httpBody), headers: headers)
And you'll get:
$>CredStore - performQuery - Error copying matching creds. Error=-25300, query={
atyp = http;
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = http;
"r_Attributes" = 1;
sdmn = someUrl;
srvr = someUrl;
sync = syna;
}
$ curl -v \
-X DELETE \
-H "Authorization: JWT someToken" \
-H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 11.4.0) Alamofire/4.7.3" \
-H "Accept-Language: en;q=1.0, fr-FR;q=0.9" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-d "id=someId" \
"http://someUrl"
Related
I'm issuing the following request:
curl --http2 -X "POST" "http://localhost:8088/query-stream"
-H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8"
-d $'{
"sql": "SELECT * FROM USERS EMIT CHANGES;",
"streamsProperties": {
"ksql.streams.auto.offset.reset": "earliest"
}
}
The result I'm getting is:
{"queryId":"cdfb3ccc-0ab5-4186-a249-b279bfc09587","columnNames":["USERID","NAME"],"columnTypes":["STRING","STRING"]}
["1","Max"]
["2","Alex"]
["13","Andrew"]
...
Is there a way I could get the data in json format?
{"userid":"1","name":"Max"}
{"userid":"2","name":"Alex"}
{"userid":"13","name":"Andrew"}
It is easier to deserialize this data into POCO objects if they are in json than to parse the 'row' format.
Per the docs you can set the Accept header. It defaults to application/vnd.ksqlapi.delimited.v1 but can also be set to application/json:
curl --show-error --silent \
-H "application/vnd.ksqlapi.delimited.v1" \
--http2 'http://localhost:8088/query-stream' \
--data-raw '{"sql":"SELECT * FROM CUSTOMERS WHERE ID=42;"}'
{"queryId":null,"columnNames":["ID","FIRST_NAME","LAST_NAME","EMAIL","GENDER","COMMENTS"],"columnTypes":["INTEGER","STRING","STRING","STRING","STRING","STRING"]}
[42,"Rick","Astley","r.astley#example.com","Male",""]
curl --show-error --silent \
-H "Accept:application/json" \
--http2 'http://localhost:8088/query-stream' \
--data-raw '{"sql":"SELECT * FROM CUSTOMERS WHERE ID=42;"}'
[{"queryId":null,"columnNames":["ID","FIRST_NAME","LAST_NAME","EMAIL","GENDER","COMMENTS"],"columnTypes":["INTEGER","STRING","STRING","STRING","STRING","STRING"]},[42,"Rick","Astley","r.astley#example.com","Male",""]]
I am using groovy execute API in Jenkins pipeline code to execute the curl command, I am getting response from the rest API, but I am not able to retrieve HTTP code.
How to retrieve the HTTP code from groovy curl execute method.
node{
stage("api")
{
getApi()
}
}
def getApi()
{
def process = ['bash', '-c',"curl -X GET --header 'Content-Type: application/json' --header 'Accept: application/json' -H 'Authorization: Bearer oosfjwejowjefojwoejfowoefjwojefwefweofjwo' https://myrest.api.com"].execute()
process.waitFor()
println (process.err.text)
println (process.text)
}
def http_code = sh(
returnStdout: true,
label: "checking myrest.api.com",
script: """curl -X GET --header 'Content-Type: application/json' \
--header 'Accept: application/json' \
-H 'Authorization: Bearer oosfjwejowjefojwoejfowoefjwojefwefweofjwo' \
https://myrest.api.com -o /dev/null -w '%{http_code}'"""
).trim()
I am sending a curl command to a server, but get an error message which I do not understand.
The request I need to send to the server is
body=$(cat << EOF
{
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)
curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer TOKEN>" \
-d "$body" \
"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"
What I do is that I translate this into a curl command like :
curlcmd = 'curl -s \ -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d "{"order": {"units": "100", "instrument": "EUR_USD", "timeInForce": "FOK", "type": "MARKET", "positionFill": "DEFAULT" }}" \ "https://api-fxpractice.oanda.com/v3/accounts/AccountID/orders"'
I send the command via resp = system (curlcmd) via Matlab to the server. What I get as an error message is :
errorMessage: 'Invalid JSON, ParseErrorCode: 4, Message: Missing a name for object member.'
Any idea what this means and how I can solve this ? I am using Matlab on Windows 10, so curl is part of Windows 10.
Response should be a placed order and response data of the trade.
The JSON doesn't seem to be properly quoted.
Try this:
curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer " -d "{\"order\": {\"units\": \"100\", \"instrument\": \"EUR_USD\", \"timeInForce\": \"FOK\", \"type\": \"MARKET\", \"positionFill\": \"DEFAULT\" }}" "https://api-fxpractice.oanda.com/v3/accounts/AccountID/orders"
Test with Proxy
With the appropriate escape of the JSON quotes, as shown in the above CURL command line, the JSON looks correct when viewed in an HTTPS proxy:
I am trying to access a remote service using "F# Data Http Utilities" but without success:
let account token = Http.RequestString("https://api.example.com/v1",
httpMethod = "POST",
headers = ["Accept", "application/json";
"Content-Type", "application/json";
"X-Application", "JRQ";
"X-Authentication", "MOl5C9ZZ";],
body = TextRequest """ {"jsonrpc": "2.0", "method": "getAccount"} """)
even though both the curl and PowerShell equivalents work correctly:
curl -i -X POST \
-H "Accept:application/json" \
-H "Content-Type:application/json" \
-H "X-Application:JRQ" \
-H "X-Authentication:MOl5C9ZZ" \
-d '{"jsonrpc": "2.0", "method": "getAccount"}' \
'https://api.example.com/v1'
What am I missing?
It seems that there is no error in the original F# code. Setting the following property:
System.Net.ServicePointManager.Expect100Continue <- false;
resolved the problem!
I set up a Restful Controller in my Grails 2.3.5 app. When sending an object via PUT to my endpoint the object won't get updated. My println does not show the updated data, but the original. I don't understand why.
Restful controller:
import grails.rest.RestfulController
class PluginSettingController extends RestfulController {
static responseFormats = ['json', 'xml']
PluginSettingController() {
super(PluginSetting)
}
#Override
def update(PluginSetting setting){
println(setting.name)
// This prints out the old name: "Old name"
}
Domain class:
class PluginSetting {
String name
String value
static constraints = {
name(nullable:false, blank:false, unique: true)
value(nullable:false, blank:false)
}
}
curl request:
curl -i -X PUT -d "{'name':'NEW','value':'my value', 'id':1}" http://localhost:8080/app/pluginSettings/1
old object (this is what i get when sending a GET to the URL 'http://localhost:8080/app/pluginSettings/1')
{
"class": "configuration.PluginSetting",
"id": 1,
"name": "Old name",
"value": "my value"
}
This finally worked for me with Grails 2.5.4 - it was suprise that the normal methods did not work when using a second controller.
#Transactional(readOnly=false) // not needed
class EngineController extends RestfulController<PluginSettings> {
static responseFormats = ['json', 'xml']
EngineController() {
super(PluginSettings)
}
}
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}
#Show
curl -i -X GET -H "Accept: application/json" localhost:8080/app/engine/index
curl -i -X GET -H "Accept: application/json" localhost:8080/app/engine/show/1
#Create
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/engine/save
#Update
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/engine/update/1
#Delete
curl -i -X DELETE http://localhost:8080/app/engine/delete/1
However when I modified the urlMappings to include
"/api/engines"(resources:"Engine")
I had to use
curl -i -X GET -H "Accept: application/json" localhost:8080/app/api/engines/
curl -i -X GET -H "Accept: application/json" localhost:8080/app/api/engines/1
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/api/engines/
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/api/engines/1
curl -i -X DELETE http://localhost:8080/app/api/engines/1