OAuth
Create Access Token
Request URL
Request parameters
(optional)
string
subscription key in url
Request headers
(optional)
string
Subscription key in header.
(optional)
string
Media type of the body sent to the API.
Request body
grant_type=password&username=user@email.com&password=yourPasswordHere
Response 200
{
"access_token": "xxxxxxxxxxxxxxxxxxxxxxx",
"expires_in": 3600,
"refresh_token": "xxxxxxxxxxxxxxxxxxxxxxx",
"token_type": "Bearer"
}
Response 400
Code samples
@ECHO OFF
curl -v -X POST "https://sandbox.azure-api.net/oauth/token?subscription-key={string}"
-H "Ocp-Apim-Subscription-Key: "
-H "Content-Type: application/x-www-form-urlencoded"
--data-ascii "{body}"
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization; //System.Web.Extensions assembly
namespace DataSmuggler
{
public class Program
{
private static void Main(string[] args)
{
var connectionString = "https://sandbox.mtapi.biz/v1/designs";
var client = CreateBasicWebRequest(connectionString);
var designs = GetResponse< List< Design > >(client);
}
private static HttpWebRequest CreateBasicWebRequest(string connectionString, string method = "GET")
{
var httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(connectionString));
httpRequest.Method = method;
httpRequest.KeepAlive = true;
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/json";
httpRequest.Headers.Add("ocp-apim-subscription-key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
httpRequest.Headers.Add("ocp-apim-developer-key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
return httpRequest;
}
private static TK GetResponse(HttpWebRequest httpRequest)
{
using (var response = httpRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return (TK)new JavaScriptSerializer().Deserialize(reader.ReadToEnd(), typeof(TK));
}
}
}
}
public class Design
{
public string Name { get; set; }
public int Number { get; set; }
public List Colors { get; set; }
public string Orientation { get; set; }
public string Size { get; set; }
public string Note { get; set; }
public string Verified { get; set; }
public string Image { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
public class Color
{
public string Name { get; set; }
public string Value { get; set; }
public int TimesUsed { get; set; }
}
}
// // 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://sandbox.azure-api.net/oauth/token");
builder.setParameter("subscription-key", "{string}");
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
// Request body
StringEntity reqEntity = new StringEntity("{body}");
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());
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</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 params = {
// Request parameters
"subscription-key": "{string}",
};
$.ajax({
url: "https://sandbox.azure-api.net/oauth/token?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","");
xhrObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString* path = @"https://sandbox.azure-api.net/oauth/token";
NSArray* array = @[
// Request parameters
@"entities=true",
@"subscription-key={string}",
];
NSString* string = [array componentsJoinedByString:@"&"];
path = [path stringByAppendingFormat:@"?%@", string];
NSLog(@"%@", path);
NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
[_request setHTTPMethod:@"POST"];
// Request headers
[_request setValue:@"" forHTTPHeaderField:@"Ocp-Apim-Subscription-Key"];
[_request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Request body
[_request setHTTPBody:[@"{body}" dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
if (nil != error)
{
NSLog(@"Error: %@", error);
}
else
{
NSError* error = nil;
NSMutableDictionary* json = nil;
NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataString);
if (nil != _connectionData)
{
json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
}
if (error || !json)
{
NSLog(@"Could not parse loaded json with error:%@", error);
}
NSLog(@"%@", json);
_connectionData = nil;
}
[pool drain];
return 0;
}
php
/*
*
* DesignName: string. The name for your artwork.
* Instructions : string
* ReplyTo : string . Used to send artwork confirmations
* Orientation : int (0 or 1). 0 is portrait and 1 is for landscape
* ItemNumber : int . The style of logo mat you'd like.
* Width : int . Measurement is in feet.
* Height : int . Measurement is in feet.
*
*/
$artworkData = array(
'Instructions' => 'This will become an awesome artwork proof.',
'ReplyTo' => YOUR_EMAIL_HERE, //replace with your E-mail
'DesignName' => 'Design Name Here',
'Orientation' => 0,
'ItemNumber' => YOUR_ITEM_NUMBER_HERE, //A list of these numbers can be obtained by using the Get Items route. https://sandbox.portal.azure-api.net/docs/services/55ac735f689d7116f8ee1136/operations/55ac735f689d7113040ae511
'Width' => 2,
'Height' => 3);
$header = array(
'Content-Type: multipart/form-data; boundary=-------------------------yourBoundaryValueHere',
'ocp-apim-subscription-key: 984bce3bd78b45a0add4e03d35cb2c58',
'ocp-apim-developer-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' //Place your developer key here
);
/* Please note that the json data string must be first in the multipart/form-data request */
$rawImageData = file_get_contents('C:\The\Local\Path\To\image.jpg');
$data = '---------------------------yourBoundaryValueHere
Content-Disposition: form-data; name="json"
Content-Type: application/json
' . json_encode($artworkData) .'
---------------------------yourBoundaryValueHere
Content-Disposition: form-data; name="fieldNameHere"; filename="Foo.jpg"
Content-Type: image/jpg
*|IMAGEDATAPLACEHOLDER|*
---------------------------yourBoundaryValueHere--';
/* Per RFC 1341, https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html,
multipart requests require CRLF line endings. The regex below formats the multipart
string with CRLF. */
$data = preg_replace("/(?<=[^\r]|^)\n/", "\r\n", $data);
$data = str_replace("*|IMAGEDATAPLACEHOLDER|*", $rawImageData, $data);
$curl_handle = curl_init();
$options = array(CURLOPT_URL => 'https://sandbox.mtapi.biz/v1/designs/artwork',
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => true, //Request header
CURLOPT_HEADER => true, //Return header
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false, //Don't verify server certificate
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($curl_handle, $options);
$result = curl_exec($curl_handle);
$header_info = curl_getinfo($curl_handle,CURLINFO_HEADER_OUT);
$header_size = curl_getinfo($curl_handle, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
curl_close($curl_handle);
?>
########### Python 2.7 #############
import httplib, urllib, base64
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': '',
'Content-Type': 'application/x-www-form-urlencoded',
}
params = urllib.urlencode({
# Request parameters
'subscription-key': '{string}',
})
try:
conn = httplib.HTTPSConnection('sandbox.azure-api.net')
conn.request("POST", "/oauth/token?%s" % params, "{body}", 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 = {
# Request headers
'Ocp-Apim-Subscription-Key': '',
'Content-Type': 'application/x-www-form-urlencoded',
}
params = urllib.parse.urlencode({
# Request parameters
'subscription-key': '{string}',
})
try:
conn = http.client.HTTPSConnection('sandbox.azure-api.net')
conn.request("POST", "/oauth/token?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
require 'net/http'
uri = URI('https://sandbox.azure-api.net/oauth/token')
uri.query = URI.encode_www_form({
# Request parameters
'subscription-key' => '{string}'
})
request = Net::HTTP::Post.new(uri.request_uri)
# Request headers
request['Ocp-Apim-Subscription-Key'] = ''
# Request headers
request['Content-Type'] = 'application/x-www-form-urlencoded'
# Request body
request.body = "{body}"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body