How, in Sinatra, to pass a Request Body to other classes? - json

I'm using a Sinatra app to receive server requests and I want to dissect them in a separate class I call "request", but when I pass the request object the body gets dropped. Trying to read the request.body in the main class works but trying to read it in the new class generates a JSONparser octet error.
In the main Sinatra file, this test call generates the correct response:
puts JSON.parse request.body.read
after, I pass the request to the Request Class with the code below.
req=Request.new(request)
But in the Request class initialization def, the same "puts" code above generates the error:
JSON::ParserError - A JSON text must at least contain two octets!:
Both files include the JSON requirement.
A work around is fairly simple but I would prefer the more elegant solution if I could figure out why it is not working as I expect. Any thoughts are appreciated.

from my tests
the Request.new constructor doesn't seem to clone from Request object
request.clone works proper
you need to do the thorough object inspection if you need anything extreme

Related

Removing headers from response in Angular Observable

Working with AWS DynamoDB to return some film JSON data to my application. There can be multiple films so I need to use an array and iterate through it to display my film list. However, I'm getting an error stating that only arrays and iterables are allowed.
I've also console.logged the response, which is below.
As you can see, my response has a body and headers, the headers are needed for my http requests to prevent cors issues, but I'm now really struggling to break the data down to Items. I'm retrieving the data from a Lambda function with an observable called IFilm[].
Above is my service code, which pipes the data to my dashboard component.
And the filmList populated in this function is what I'm trying to iterate through in my html using an *ngFor. When trying to use .body or the likes on the response, I receive this error.
I feel like I'm so close to cracking this, so any advice is appreciated and if any clarification is required just ask :)
Thanks.
[edit in case anyone suggests this]
I've also tried using next, complete, error in my .subscribe but had no luck.
[edit 2]
So I tried using response['body'] and received this message.
And I also tried using the second suggestion, changed some things around a little but now it's gone very weird.
[edit 3]
Sorry my mistake, I had missed one of the changes. My service is now red line free, but the error about missing length, pop, concat, has moved to my dashboard component.
[edit 4]
Fixed it, for any future readers here's what I did. When making an API call to my Lambda function I had to have the headers and body returned. I was trying to take this data and pass it, both headers and body, into my IFilm model. Instead, what I needed to do was create an IResponse model, parse some of the data from that and then populate my IFilm[] using my IResponse.
And below is the code in my dashboard component for populating my IFilm array.
Why are you set the _http, with the new HttpClient()? It is injected by Dependency Injection if you put the HttpClientModule into the AppModule imports array.
Also you specified the generic return type IFilm[] so if you get back a HttpResponse with a body parameter and IFilm[] in it you have to specify as a HttpResponse<IFilm[]>.
So the actual code is:
this._http.get<HttpResponse<IFilm[]>>(...)
Plus the return value of the getFilmList should be Observable<HttpResponse<IFilm[]>>.
More about the HttpResponse here: https://angular.io/api/common/http/HttpResponse
[Update]
Then if you updated, you can get the films by response.body.
this.filmList = response.body;

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)

Grails - Do you still need parseRequest for JSON binding to work in controller?

Ok, this is my Nth question regarding this topic, and I'm getting really frustrated with Grails. Please have a quick look on one of my earlier questions for more details.
Among other things, my problem is that sending JSON formatted data to the controller when testing doesn't seem to work. The controller doesn't get null object, but the argument passed is practically empty--the JSON properties don't get set.
Aside from the controller code from the link above, I also tried,
def save() {
def model = new MyModel(request.JSON)
model.save()
}
but it still fails to set properties.
From my Web searches, I read that in older versions, parseRequest must be set to true in UrlMapping.groovy so that request data formatted in XML, JSON, etc. would automatically be parsed and passed as controller method argument. I'm working on Grails 2.3.9, and I'm not sure if it's still necessary to do that.
The time I thought I'd save if I use Grails on this project is being spent on looking for an answer to this seemingly simple task of testing a RESTful Web service.
No since 2.3.0 the parseRequest option doesn't do anything. The request is parsed lazily only when request.XML or request.JSON is accessed or when binding to a command object.

How can I enable GZIP compression of the JSON response entity on Reslet?

I have a Restlet application already working that accepts JSON and returns JSON entity as response.
I'm trying to understand how I can compress the JSON entity that is returned in the response.
I did not find any clear example on how to achieve it.
I think I have to put somewhere on the router chain the Encoder/EncoderService classes, but I really don't understand where and how to use them.
Could anybody help me?
After some testing, I got the answer.
Creating a new filter like this
Filter encoder = new Encoder(getContext(), false, true, new EncoderService(true));
inside the createInboundRoot() method of my own Application class did the trick, the client requests were already containing the gzip header needed.