0

How can I validate the REST payloads (xml) against a schema definition?

What should the XSD define at minimum?

would it be a good practice to provide xsds for my rest payloads in XML so the consumers can validate against these xsds before making a call?

user1983
  • 21
  • 2
  • 7

1 Answers1

0

So you might get more answers ont his if you tag it with Java, but based on this post (Validating XML against XSD ( you want something like this:

static boolean validateAgainstXSD(InputStream xml, InputStream xsd)
{
  try
  {
    SchemaFactory factory = 
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new StreamSource(xsd));
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(xml));
    return true;
  }
  catch(Exception ex)
  {
    return false;
  }
}

Your XSD should define all elements, attributes, and records in the XML document, as well as how often they can occur and whether they're nillable at a minimum. I don't know of a well defined way to provide a WSDL using REST, but you might consider having some API call through your interface that basically provides the WSDL/XSD you're using for consumers.

With that said, why don't you just use a SOAP based interface for this? REST is great and has its place, but it sounds like you're looking for a messaging protocol with strong types and contracts - which is what SOAP is more designed for.

Community
  • 1
  • 1
Dan Field
  • 20,885
  • 5
  • 55
  • 71