validate POST data from swagger json.schema in node - json

In a swagger spec, I define the schema of the object that is returned by a query. That's great for GETs but if I have a POST endpoint, it could have that same object in it. Can I specify a json.schema for the "parameters" that are POSTed to an endpoint? That is do a $ref: #/definitions/myObject? It would suck to have to define the schema twice, once for incoming and once for outgoing.
And then is it possible to have middleware validate the payload of a post against that json.schema and reject if the payload does not comply?
It seems that all the pieces are available, so now I'm wondering if it's been pulled together or not.

Ok, seems I can't discover anything before posting in desperation. But I found it.
In the docs, surprisingly. Paramnerters. If you declare a parameter type of "body" then you can/must declare a schema type. As in json.schema. So that's part one.
Then for part two there is middleware for node in swagger-tools that validates the request and optionally the response. While it's not exactly explicit I believe that it will validate the body against the schema, so that's pretty cool. I don't know what kind of error messages it generates, hopefully something either configurable or at least intelligible.

Related

Does json.Compact also validate json?

A colleague and I were trying to write the minimal logic that we needed for compacting, validating, parsing, and storing json coming from a client.
Upon doing so, we realized that compacting and validating were two steps that were both being accomplished by json.Compact anyways, since the code indicates json.Compact calls the json Scanner. The scanner then validates json and errors on invalid json.
The docs do not make this explicit, but we think this is the case.
Here is a link: https://forum.golangbridge.org/t/json-compact-appears-to-also-validate-json-but-is-not-documented/23088
Let us know thoughts.
Yes.
json.Compact uses json.scanner while scanning the json. If the scanner encounters invalid JSON sets scanner.err, which is returned by json.Compact if there is an error.
This is the same way json.Valid checks for valid json, by simply scanning the JSON and checking for scanner.err.
Here's the relevant code sections:
https://go.googlesource.com/go/+/go1.16.2/src/encoding/json/indent.go#17
https://go.googlesource.com/go/+/go1.16.2/src/encoding/json/scanner.go#30

Can you expect JSON schema compliant data from a RAML API or is it just for posting data?

I am talking to an API that uses RAML. I am both downloading and uploading data to it.
When uploading data I had previously downloaded, I got a JSON Schema violation error, saying some of the parameters in the JSON objects were not allowed.
I realize the data i received is not following the JSON schema.
Is this kind of behavior a violation against the RAML principles?
What columns you GET and what columns you are allowed to POST may not be the same. For example, if you GET a user, it might include a user_id column, but you usually won't be allowed to write to it!
It's difficult to give a fuller answer without seeing the RAML spec document.
It's totally possible and valid to define different schemas for each HTTP method.

Make sure an incoming JSON response conforms to a schema?

I use Alamofire to interact with the server API via JSON requests/responses. I want to make sure server responds with some strictly formed payload to my requests.
How do I check that, for example, in {"responseCode":15, "data":{"username":"maxpayne", "fullname":"Max Payne", "score":154, friends:["johndoe", "franksinatra"]}}, responseCode is a number, username and fullname are strings, and friends is an array of strings?
I can do it manually for each response, but seems like it's going to be the most worthless time waste.
Alamofire has .validate() method but it is created for different purpose as what I see. I also had a look at JSONSchemaSwift which seems to be a right solution, but is not in active development.
As an alternative, it could be good to have a JSON deserializer which validates a response automatically and creates an object based on a Swift class I define.
May be a bit late, but this came out kylef/JSONSchema.swiftcame out on github. It's a JSONSchema validator, simple and effective.

Why do I get loose closing brackets for my Django Rest Framework endpoint?

Here's my JSON response for http://localhost:8000/characters/api/users/1?format=json
)]}',
{"id":1,"username":"admin","mage_by_user":[3],"mage_last_updated":"2015-02-11T16:13:16.229Z"}
Notice the )]}', on the first line.
Here is my code that gets called to create the JSON:
class UserSerializer(serializers.ModelSerializer):
mage_by_user = serializers.PrimaryKeyRelatedField(
many=True, queryset=Mage.objects.all())
mage_last_updated = serializers.ReadOnlyField(
source='mage_by_user.updated_date')
class Meta:
model = User
fields = ('id', 'username', 'mage_by_user', 'mage_last_updated',)
Further testing:
I've noticed the title of the page is TypeError at <insert url here>.
This happens with all of my endpoints
If I try to access a non-existent object (userId=2 for instance), then renders 'normally' for DRF, e.g:
{
detail: "Not found"
}
Any idea why this would happen?
Those characters are inserted by the Djangular middleware AngularJsonVulnerabilityMiddleware, to inject Json Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.
Unfortunately, it means it breaks various JSON viewers.
Sorry to not be more help, but this looks like something entirely unrelated to REST framework. There's absolutely no way a JSON response there would ever be rendered in that way.
Perhaps you have a custom renderer configured, that's outputting a malformed response, perhaps you have some broken middleware inserting those characters, perhaps its an issue in the client or whatever environment you're making the requests, or perhaps it's something else entirely unrelated to any of those.
I'd start by trying to narrow down the issue as much as possible - remove all the complexity from the view and serializer and attempt to replicate the behavior in a test case.
Most likely there's some sort of unexpected integration issue you're missing or some otherwise obvious code typo that's being overlooked.

Pentaho HTTP Post using JSON

I'm brand new to Pentaho and I'm trying to do the following workflow:
read a bunch of lines out of a DB
do some transformations
POST them to a REST web service in JSON
I've got the first two figured out using an input step and the Json Output step.
However I have two problems doing the final step:
1) I can't get the JSON formatted how I want. It insists on doing {""=[{...}]} when I just want {...}. This isn't a big deal - I can work around this since I have control over the web service and I could relax the input requirements a bit. (Note: this page http://wiki.pentaho.com/display/EAI/JSON+output gives an example for the output I want by setting no. rows in a block=1 and an empty JSON block name, but it doesn't work as advertised.)
2) This is the critical one. I can't get the data to POST as JSON. It posts as key=value, where the key is the name I specify in the HTTP Post field name (on the 'Fields' tab) and the value is the encoded JSON. I just want to post the JSON as the request body. I've tried googling on this but can't find anyone else doing it, leading me to believe that I'm just approaching this wrong. Any pointers in the right direction?
Edit: I'm comfortable scripting (in Javascript or another language) but when I tried to use XmlHttpRequest in a custom javascript snippet I got an error that XmlHttpRequest is not defined.
Thanks!
This was trivial...just needed to use the REST Client (http://wiki.pentaho.com/display/EAI/Rest+Client) instead of the HTTP Post task. Somehow all my googling didn't discover that, so I'll leave this answer here in case someone else has the same problem as me.
You need to parse the JSON using a Modified JavaScript step. e.g. if the Output Value from the JSON Output is called result and its contents are {"data"=[{...}]}, you should call var plainJSON = JSON.stringify(JSON.parse(result).data[0]) to get the JSON.
In the HTTP Post step, the Request entity field should be plainJSON. Also, don't forget to add a header for Content-Type as application/json (you might have to add that as a constant)