Hello I’m trying to translate POST request api code written in php:
<?php
$methodParams = '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);
To Swift but I don’t have idea why it doesn’t work:
import UIKit
struct Parameters: Codable {
let date_confirmed_from: Int
let get_unconfirmed_orders: Bool
}
struct BodyData: Codable {
let method: String
let parameters:Parameters
}
let url = URL(string: "https://api.baselinker.com/connector.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = [
"X-BLToken": "xxx"
]
let bodyData = BodyData(method: "getOrders", parameters: Parameters(date_confirmed_from: 1407341754, get_unconfirmed_orders: false))
let encoder = JSONEncoder()
do {
let encodeData = try encoder.encode(bodyData)
request.httpBody = encodeData
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print(error)
}
if let data = data {
}
}
task.resume()
}catch {
print(error)
}
When I’m testing my Swift code I’m getting error answer from API can someone help me to find fault in my code?
2
Answers
Okay I find out solution for this problem:
The biggest problem was coding of data. curl in PHP by default sending data as x-www-form-urlencoded
Does the PHP curl work?
It is not what the baseline documentation is asking for.
The documentation asks for this post data:
Your PHP curl request post data:
The documentation asks
parameters = arguments of the requested function in JSON format.
Your parameters are an array, not JSON.