简体   繁体   中英

Validate REST payloads against their associated XML schema definition (XSD)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM