For non required fields, you can either omit from the JSON string or set it to a default value
(e.g. String = "", Integer/Double = 0, Boolean = false, DateTime = 1900-01-01T00:00:00.000Z)
{"auth": {"api_username": "", "api_password": "", "api_key": "", "company_no": 0, "username": "", "password": "", "timezone_offset": 0, "auth_type": "", "system_name": "", "system_company_no": 0 }, "fields": {"mobile_number": "", "order_no": 0, "company_no": 0, "first_name": "", "email": "", "message_subject": "", "customer_no": 0, "message_body": "" } }
{"auth": {"api_username": "", "api_password": "", "api_key": "", "company_no": 0, "username": "", "password": "" }, "fields": {"mobile_number": "", "order_no": 0, "company_no": 0, "first_name": "", "email": "", "message_subject": "", "customer_no": 0, "message_body": "" } }
This sample code is to generate a function leveraging existing core functions you've already built.
func getAPIKit() -> (url: String, dict: Dictionary<String, AnyObject>) {
var mobile_number = ""
var order_no = 0
var company_no = 0
var first_name = ""
var email = ""
var message_subject = ""
var customer_no = 0
var message_body = ""
let url = "https://api.peoplevine.com/commerce.asmx/emailOrder"
let key = "fields"
let fieldsDict: Dictionary<String, AnyObject> = ["mobile_number": mobile_number, "order_no": order_no, "company_no": company_no, "first_name": first_name, "email": email, "message_subject": message_subject, "customer_no": customer_no, "message_body": message_body ]
let finalDict = User.getAuthDict(dictToAdd: fieldsDict, dictKey: key)
return (url, finalDict)
}
To get started we reccomend that you download the Alamofire project to simplify integration: https://github.com/Alamofire/Alamofire, in addition to SwiftyJSON: https://github.com/SwiftyJSON/SwiftyJSON
import Foundation
struct AUTH {
static var api_username = <string>
static var api_password = <string>
static var api_key = <string>
static var company_no = <double>
static var username = <string>
static var password = <string>
static var timezone_offset = <double>
static var auth_type = <string>
static var system_name = <string>
static var system_company_no = <double>}
struct FIELDS {
static var mobile_number = <string>
static var order_no = <double>
static var company_no = <double>
static var first_name = <string>
static var email = <string>
static var message_subject = <string>
static var customer_no = <double>
static var message_body = <string>}
func emailOrderRequest() {
var emailOrderObjects = [AnyObject]()
let postsEndpoint: String = "https://api.peoplevine.com/commerce.asmx/emailOrder"
let authAndFieldsDict = ["auth": ["api_username": AUTH.api_username, "api_password": AUTH.api_password, "api_key": AUTH.api_key, "company_no": AUTH.company_no, "username": AUTH.username, "password": AUTH.password, "timezone_offset": AUTH.timezone_offset, "auth_type": AUTH.auth_type, "system_name": AUTH.system_name, "system_company_no": AUTH.system_company_no ], "fields": ["mobile_number": FIELDS.mobile_number, "order_no": FIELDS.order_no, "company_no": FIELDS.company_no, "first_name": FIELDS.first_name, "email": FIELDS.email, "message_subject": FIELDS.message_subject, "customer_no": FIELDS.customer_no, "message_body": FIELDS.message_body ] ]
Alamofire.request(.POST, postsEndpoint, parameters: authAndFieldsDict, encoding: .JSON).responseJSON { (request, response, data, error) in
if let anError = error {
println("error calling POST on /posts")
println(error)
} else if let jsonData: AnyObject = data {
if let dataString = (jsonData.valueForKey("d") as! String).dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: dataString) //use this object to parse data
//SAMPLE PARSING
let varData = json["returnObject"][0]["object"].stringValue
// ----------
// BELOW REPRESENTS AN EXAMPLE USING PURE SWIFT JSONSERIALIZATION INSTEAD OF SWIFTYJSON --------//
// if let emailOrderDict = NSJSONSerialization.JSONObjectWithData(encoString, options: .MutableContainers, error: nil) as? NSDictionary {
// if let returnObjectArray = emailOrderDict["returnObject"] as? NSArray {
//
// for emailOrderObject in returnObjectArray {
// emailOrderObjects.append(emailOrderObject)
// if let item = emailOrderObject["object_name"] as? NSDictionary {
// let varItem = item["field_name"] as! String
// }
// }
//
// println("\n\(emailOrderObjects.count) Total")
// }
// }
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>API Call - emailOrder</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var dataValue = {
"auth": {
"api_username": "",
"api_password": "",
"api_key": "",
"company_no": 0,
"username": "",
"password": "",
"timezone_offset": 0,
"auth_type": "",
"system_name": "",
"system_company_no": 0,
},
"fields": {
"mobile_number": "",
"order_no": 0,
"company_no": 0,
"first_name": "",
"email": "",
"message_subject": "",
"customer_no": 0,
"message_body": "",
},
};
$.ajax({
url: 'https://api.peoplevine.com/commerce.asmx/emailOrder',
type: 'POST',
data: JSON.stringify(dataValue),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("ERROR");
},
success: function (result) {
var obj = JSON.parse(result.d).returnObject;
$.each(obj, function(i) {
$("#divID").html(obj[i].field_name); //do something with the data
})
}
})
});
</script>
</body>
</html>
System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create("https://api.peoplevine.com/commerce.asmx/emailOrder");
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";
string dataValue = "{auth: {api_username: <string>, api_password: <string>, api_key: <string>, company_no: <double>, username: <string>, password: <string>, timezone_offset: <double>, auth_type: <string>, system_name: <string>, system_company_no: <double> },fields: {mobile_number: <string>, order_no: <double>, company_no: <double>, first_name: <string>, email: <string>, message_subject: <string>, customer_no: <double>, message_body: <string> }}";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(dataValue);
req.ContentLength = bytes.Length;
System.IO.Stream strm = req.GetRequestStream();
strm.Write(bytes, 0, bytes.Length);
strm.Close();
System.Net.HttpWebResponse rsp = req.GetResponse();
System.IO.Stream data = rsp.GetResponseStream();
System.IO.StreamReader rdr = new System.IO.StreamReader(data);
string response = rdr.ReadToEnd();
Dim req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://api.peoplevine.com/commerce.asmx/emailOrder")
req.Method = "POST"
req.ContentType = "application/json; charset=utf-8"
Dim dataValue As String = "{auth: {api_username: <string>, api_password: <string>, api_key: <string>, company_no: <double>, username: <string>, password: <string>, timezone_offset: <double>, auth_type: <string>, system_name: <string>, system_company_no: <double> },fields: {mobile_number: <string>, order_no: <double>, company_no: <double>, first_name: <string>, email: <string>, message_subject: <string>, customer_no: <double>, message_body: <string> }}"
Dim encoding As New ASCIIEncoding()
Dim bytes As Byte() = encoding.GetBytes(dataValue)
req.ContentLength = bytes.Length
Dim strm As System.IO.Stream = req.GetRequestStream()
strm.Write(bytes, 0, bytes.Length)
strm.Close()
Dim rsp As System.Net.HttpWebResponse = req.GetResponse()
Dim data As System.IO.Stream = rsp.GetResponseStream()
Dim rdr As New System.IO.StreamReader(data)
Dim response As String = rdr.ReadToEnd()
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class JavaSample {
public static void main(String[] args) {
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://peoplevine.azure-api.net/customer/customer/registerCustomer");
// Specify your subscription key
builder.setParameter("subscription-key", "");
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
StringEntity reqEntity = new StringEntity("", ContentType.create("application/json"));
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
<?php
// This sample uses the HTTP_Request2 package. (for more information: http://pear.php.net/package/HTTP_Request2)
require_once 'HTTP/Request2.php';
$headers = array(
'Content-Type' => 'application/json',
);
$query_params = array(
// Specify your subscription key
'subscription-key' => '',
);
$request = new Http_Request2('https://peoplevine.azure-api.net/customer/customer/registerCustomer');
$request->setMethod(HTTP_Request2::METHOD_POST);
// Basic Authorization Sample
// $request-setAuth('{username}', '{password}');
$request->setHeader($headers);
$url = $request->getUrl();
$url->setQueryVariables($query_params);
$request->setBody("");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
#import <Foundation/Foundation.h>
NSDictionary *authDic = [NSDictionary dictionaryWithObjectsAndKeys:
<string>, @"api_username",
<string>, @"api_password",
<string>, @"api_key",
<double>, @"company_no",
<string>, @"username",
<string>, @"password",
<double>, @"timezone_offset",
<string>, @"auth_type",
<string>, @"system_name",
<double>, @"system_company_no", nil];
NSDictionary *fieldsDic = [NSDictionary dictionaryWithObjectsAndKeys:
<string>, @"mobile_number",
<double>, @"order_no",
<double>, @"company_no",
<string>, @"first_name",
<string>, @"email",
<string>, @"message_subject",
<double>, @"customer_no",
<string>, @"message_body", nil];
NSDictionary *finalDic = [NSDictionary dictionaryWithObjectsAndKeys:
authDic, @"auth",fieldsDic, @"fields", nil];
NSMutableDictionary* jsonString = nil;
jsonString = [NSJSONSerialization JSONObjectWithData: findalDic options:NSJSONReadingMutableContainers];
NSMutableData *bodyData = [NSMutableData dataWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
NSString *urlString = @"https://api.peoplevine.com/commerce.asmx/emailOrder";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setTimeOutSeconds:250];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request addRequestHeader:[NSString stringWithFormat:@"%d",bodyData.length] value:@"Content-length"];
[request setPostBody:bodyData];
[request startSynchronous];
NSDictionary *responseDic = (NSDictionary*)[request.responseString JSONValue];
if (responseDic || [responseDic objectForKey:@"d"])
{
NSMutableDictionary *dicSave=[responseDic objectForKey:@"d"];
// -------------------------------------------------------------------
// convert into the data and NSUTF8StringEncoding
// -------------------------------------------------------------------
NSString *strDic=[dicSave copy];
NSMutableDictionary *dirJson;
if (strDic)
{
NSData* dataFile=[strDic dataUsingEncoding:NSUTF8StringEncoding];
NSString* newStr = [[NSString alloc] initWithData:dataFile
encoding:NSUTF8StringEncoding];
dirJson = [newStr JSONValue] ;
}
// -------------------------------------------------------------------
NSString *str=[[dirJson objectForKey:@"returnObject"]valueForKey:@"customer_no"];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error" message:@"An Error Occurred" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
require 'net/http'
uri = URI('https://peoplevine.azure-api.net/customer/customer/registerCustomer')
uri.query = URI.encode_www_form({
# Specify your subscription key
'subscription-key' => '',
})
request = Net::HTTP::Post.new(uri.request_uri)
# Basic Authorization Sample
# request.basic_auth 'username', 'password'
request['Content-type'] = 'application/json'
request.body = ""
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body
########### Python 2.7 #############
import httplib, urllib, base64
headers = {
# Basic Authorization Sample
# 'Authorization': 'Basic %s' % base64.encodestring('{username}:{password}'),
'Content-type': 'application/json',
}
params = urllib.urlencode({
# Specify your subscription key
'subscription-key': '',
})
try:
conn = httplib.HTTPSConnection('peoplevine.azure-api.net')
conn.request("POST", "/customer/customer/registerCustomer?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Basic Authorization Sample
# 'Authorization': 'Basic %s' % base64.encodestring('{username}:{password}'),
'Content-type': 'application/json',
}
params = urllib.parse.urlencode({
# Specify your subscription key
'subscription-key': '',
})
try:
conn = http.client.HTTPSConnection('peoplevine.azure-api.net')
conn.request("POST", "/customer/customer/registerCustomer?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
@ECHO OFF
REM for Basic Authorization use: --user {username}:{password}
REM Specify values for path parameters (shown as {...}), your subscription key and values for query parameters
curl -v -X POST "https://peoplevine.azure-api.net/customer/customer/registerCustomer?subscription-key="^
-H "Content-Type: application/json"