Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Optional XML API response output support (refactored) #4

Open
wants to merge 8 commits into from

1 participant

@richtr

This patch adds support for XML output to be returned if an 'X-Output-Format: xml' HTTP header has been sent from the API client.


Server-side API compliment to pull request #2 for mashape-api-proxy:

Mashape/Mashape-API-Proxy#2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 25, 2011
  1. Revert previous XML generation code

    Rich Tibbett authored
  2. Refactoring of the XML response generation code

    Rich Tibbett authored
Commits on Nov 26, 2011
  1. Add XmlGeneratour code

    Rich authored
  2. Add _latest_ XmlGenerator code

    Rich authored
  3. Fix response on error output

    Rich authored
  4. Trigger XML mode on HTTP X-Output-Format header instead of querystrin…

    Rich authored
    …g output parameter
This page is out of date. Refresh to see the latest.
View
8 mashape/mashape.php
@@ -30,6 +30,10 @@
abstract class MashapeRestAPI {
private static $errors;
+
+ public static $toXml = false;
+ public static $xmlRoot = 'result';
+
public $dirPath;
protected function __construct($dirPath) {
@@ -52,6 +56,10 @@ public static function setHTTPStatusCode($statusCode) {
header("HTTP/1.0 " . $statusCode);
}
}
+
+ public static function setRoot($name = 'result') {
+ self::$xmlRoot = $name;
+ }
public static function parseBoolean($value) {
if ($value == "1" || strtolower($value) === "true") {
View
2  mashape/methods/call/call.php
@@ -45,6 +45,8 @@ public function handle($instance, $serverKey, $parameters, $httpRequestMethod) {
$this->findMethod($parameters, $methodName, $method, $serverKey, $httpRequestMethod);
+ $instance::$xmlRoot = $methodName;
+
if (strtolower($method->getHttp()) != strtolower($httpRequestMethod)) {
throw new MashapeException(EXCEPTION_INVALID_HTTPMETHOD, EXCEPTION_INVALID_HTTPMETHOD_CODE);
}
View
62 mashape/methods/handler.php
@@ -29,6 +29,7 @@
require_once(dirname(__FILE__) . "/../net/httpUtils.php");
require_once(dirname(__FILE__) . "/discover/discover.php");
require_once(dirname(__FILE__) . "/call/call.php");
+require_once(dirname(__FILE__) . "/../xml/xmlGenerator.php");
define("OPERATION", "_op");
define("CALLBACK", "callback");
@@ -59,10 +60,12 @@ private static function validateCallback($callback) {
public static function handleAPI($instance, $serverKey) {
header("Content-type: application/json");
+ $operation;
try {
if ($instance == null) {
throw new MashapeException(EXCEPTION_INSTANCE_NULL, EXCEPTION_SYSTEM_ERROR_CODE);
}
+
$requestMethod = (isset($_SERVER['REQUEST_METHOD'])) ? strtolower($_SERVER['REQUEST_METHOD']) : null;
$params;
if ($requestMethod == 'post') {
@@ -74,6 +77,11 @@ public static function handleAPI($instance, $serverKey) {
} else {
throw new MashapeException(EXCEPTION_NOTSUPPORTED_HTTPMETHOD, EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE);
}
+
+ var $outputFormat = HttpUtils::getHeader("X-Output-Format");
+ if(!empty($outputFormat) && $outputFormat == 'xml') {
+ $instance::$toXml = true;
+ }
$operation = (isset($params[OPERATION])) ? $params[OPERATION] : null;
unset($params[OPERATION]); // remove the operation parameter
@@ -97,17 +105,24 @@ public static function handleAPI($instance, $serverKey) {
throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE);
}
- $jsonpCallback = (isset($params[CALLBACK])) ? $params[CALLBACK] : null;
- if (empty($jsonpCallback)) {
- // Print the output
- echo $result;
- } else {
- if (self::validateCallback($jsonpCallback)) {
- echo $jsonpCallback . '(' . $result . ')';
- } else {
- throw new MashapeException(EXCEPTION_INVALID_CALLBACK, EXCEPTION_SYSTEM_ERROR_CODE);
- }
- }
+ if($instance::$toXml && $operation === "call") {
+ $JSONd = json_decode($result);
+ header("Content-type: application/xml");
+ $xmlResult = new XMLGenerator($JSONd, $instance::$xmlRoot);
+ echo $xmlResult->toXML();
+ } else {
+ $jsonpCallback = (isset($params[CALLBACK])) ? $params[CALLBACK] : null;
+ if (empty($jsonpCallback)) {
+ // Print the output
+ echo $result;
+ } else {
+ if (self::validateCallback($jsonpCallback)) {
+ echo $jsonpCallback . '(' . $result . ')';
+ } else {
+ throw new MashapeException(EXCEPTION_INVALID_CALLBACK, EXCEPTION_SYSTEM_ERROR_CODE);
+ }
+ }
+ }
} else {
// Operation not supported
@@ -157,11 +172,32 @@ public static function handleAPI($instance, $serverKey) {
header("HTTP/1.0 500 Internal Server Error");
break;
}
- echo JsonUtils::serializeError($e->getMessage(), $code);
+ if($instance && $instance::$toXml) {
+ header("Content-type: application/xml");
+ $errorArr = array(
+ 'message' => $e->getMessage(),
+ 'code' => $code
+ );
+ $xmlResult = new XMLGenerator($errorArr, 'error');
+ echo $xmlResult->toXML();
+ } else {
+ echo JsonUtils::serializeError($e->getMessage(), $code);
+ }
} else {
//Otherwise print a "generic exception" code
header("HTTP/1.0 500 Internal Server Error");
- echo JsonUtils::serializeError($e->getMessage(), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
+
+ if($instance && $instance::$toXml) {
+ header("Content-type: application/xml");
+ $errorArr = array(
+ 'message' => $e->getMessage(),
+ 'code' => EXCEPTION_GENERIC_LIBRARY_ERROR_CODE
+ );
+ $xmlResult = new XMLGenerator($errorArr, 'error');
+ echo $xmlResult->toXML();
+ } else {
+ echo JsonUtils::serializeError($e->getMessage(), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
+ }
}
}
}
View
77 mashape/xml/xmlGenerator.php
@@ -0,0 +1,77 @@
+<?php
+ /**
+ * JSON to XML Generator / Convertor
+ *
+ * Author: Richard Tibbett, 2011
+ */
+class XMLGenerator {
+
+ var $json;
+ var $rootName;
+
+ function XMLGenerator($json, $rootName = 'result') {
+ $this->json = $json;
+ $this->rootName = $rootName;
+ }
+
+ public function toXML() {
+ try {
+ $this->dom = new DOMDocument('1.0', 'utf-8');
+ return $this->Parse($this->json);
+ } catch(Exception $e) {}
+ $this->dom = new DOMDocument('1.0', 'utf-8');
+ $this->dom->appendChild( $this->dom->createElement($this->rootName) );
+ return $this->dom->saveXML();
+ }
+
+ private function Parse($json, $node = false) {
+ $root = false;
+ if (empty($node)) {
+ $node = $this->dom->createElement($this->rootName);
+ $root = true;
+ }
+ foreach ($json as $key => $val) {
+ if(is_array($val)) {
+ foreach ($val as $skey => $sval) {
+ if(is_object($sval)) {
+ $node->appendChild($this->Parse($sval, $this->dom->createElement($key)));
+ } else {
+ $node->appendChild($this->dom->createElement($key, $sval));
+ }
+ }
+ } elseif (is_object($val)) {
+ foreach ($val as $skey => $sval) {
+ if(!isset($currentKey) || $key !== $currentKey) $nNode = $this->dom->createElement($key);
+ $node->appendChild($this->Parse(array($skey => $sval), $nNode));
+ $currentKey = $key;
+ }
+ } else {
+ // fix boolean output
+ if($val === true) {
+ $val = "true";
+ } elseif($val === false) {
+ $val = "false";
+ }
+ $node->appendChild($this->dom->createElement($key, $val));
+ }
+ }
+ if ($root == true) {
+ $this->dom->appendChild($node);
+ return $this->dom->saveXML();
+ } else {
+ return $node;
+ }
+ }
+}
+
+
+/*
+// TEST
+// - Enable this block and execute this file.
+
+$jsonTestStr = '{"simpleval0":1.2,"simpleval1":"http:\/\/foo.com\/bar\/","objval":{"foo":"bar","baz":10},"arrayval":["50", "60", "70"],"arrayobjval":[{"foo":"bar","baz":30}, {"foo":"bar","baz":40}],"recursivetest":{"simpleval0":1.4,"simpleval1":"http:\/\/foo.com\/bar\/","objval":{"foo":"bar","baz":100},"arrayval":["500", "600", "700"],"arrayobjval":[{"foo":"bar","baz":300}, {"foo":"bar","baz":400}]}}';
+$json = json_decode($jsonTestStr);
+
+$xmlgen = new XMLGenerator($json, 'jsontoxml');
+echo $xmlgen->toXML();
+*/
Something went wrong with that request. Please try again.