Backbone.js sync using post variables, not json - json

I'm new to backbone and trying to write an html5 front end for an existing (and pretty big) REST back end. I found that when saving a model, backbone by default sends the model encoded as JSON which my existing API doesn't support.
Is it possible to send plain simple post request with variables using backbone?

I think what you're looking for is Backbone.emulateJSON = true
copied from the official documentation:
If you're working with a legacy web server that can't handle requests
encoded as application/json, setting Backbone.emulateJSON = true; will
cause the JSON to be serialized under a model parameter, and the
request to be made with a application/x-www-form-urlencoded mime type,
as if from an HTML form.

Related

Does using multipart/form-data Content Type for a RESTful POST api a good practice?

I have a situation where I have to write a api to create a resource and amongst datafields that I need to accept is a string that is basically contents of a html file. As I see it I have a choice between structuring the entire thing as a json object where this field is a string field with urlencoded html string , and having the Content Type as multipart/form-data where each of the fields and the html string (UTF-8 encoded) is a part in the message.
Not using json is something I am not comfortable with as I feel violating the REST standards in not structuring the content of the entity I am about to create thus there is a loss of information for the consumers as they can't tell immediately looking at my api definition about what data to feed to it. But practically multipart/form-data handles stuff like html file content better and more efficient as I will not have to urlencode it and can control the char-encoding also.
What will be a better approach in current context and upholding RESTful principles ? Also are there other trade-offs i should be aware of ? what about parsing a json with a huge string field (~ 200 Kb)embedded?
EDIT :- I was reading some similar questions on SO and one approach that stood out was the 2-step approach of making a first call with metadata to create the entity and then upload the file as an UPDATE process to the created entity wherein we use multipart/form-data. In that context, I guess , what I am asking is how sound is an approach where I send both metadata and the file in a single api call as multipart data , where each metadata field is actually a part in the multipart message as is the file.
The canonical way to upload files to REST API is using the multipart/form-data. As W3 recommendation guide says:
The content type "multipart/form-data" should be used for submitting
forms that contain files, non-ASCII data, and binary data.
Multipart/form-data has advantages over base64 to represent binary data. Is sticked to REST/Http philosophy, and simplify the develop of API clients.
Returning values from Forms: multipart/form-data
W3 Recommendation guide
The good practice is to use multipart/form-data whenever files are uploaded to the server along with database fields. Do not send a base64 JSON string as the request to your Rest API as it might corrupt the file or degrade the performance of your application.
As far as documenting multipart/form-data Rest API for your consumers is concerned you have to force your API consumers to use the same form fields which you have predefined in your web service.
Returning Values from Forms: multipart/form-data
I started using FormData objects everywhere on the client-side, in lieu of regular form input fields, for dynamic REST posts. FormData is presented in a positive light in various tutorials, so I went with it.
However, down the line, this caused me problems when decoding the form data into my Go structs. FormData objects are sent as "multipart/form-data" (regardless of files being sent) and I believe my decoder in Go didn't convert the raw data back to string form. Eventually my SQL queries were throwing panics, as hex data was being sent in where strings should have been.
So with some adjustment, I could use FormData however I've decided to revert to the simple universal recommendation: Use "multipart/form-data" only for special cases like when sending files. Otherwise, just use regular "application/x-www-form-urlencoded".

ASP MVC Return JSON

I am working on a web API with ASP.NET MVC (.NET 4.5.2) (I'm quite new to ASP) and I would like the change to response format from my controller to be JSON instead of XML.
I tried several things like using the ActionResult return type and returning something like new Json() but this function is not recognized and Visual Studio asks me to create the function.
I'm not sure I'm giving you enough info to help me, so please ask me for more if necessary :)
Thanks!
All you need to do is this:
[HttpGet]
public object Test(string testparameters)
{
return new {decision = "enable"};
}
If you are making use of an ApiController, the client (probably the browser that makes the HTTP request) should specify which type it is expecting.
When the client sends a request message, it can include an Accept
header. The Accept header tells the server which media type(s) the
client wants from the server. For example:
Accept: text/html,application/xhtml+xml,application/xml
This header tells the server that the client wants either HTML, XHTML,
or XML.
The media type determines how Web API serializes and deserializes the
HTTP message body. Web API has built-in support for XML, JSON, BSON,
and form-urlencoded data, and you can support additional media types
by writing a media formatter.
See Media Formatters in ASP.NET Web API 2.
In your case, your request should contain Accept: application/json

Why not use content negotiation to return JSON object?

I'm using content negotiation to return a JSON object from some WebAPI controllers.
I found this question
How to return Json object on Web API Controller
Here some of the people answered seem to agree that you shouldn't rely on negotiation but should create a new HttpContent class for the JSON return.
Why is this please? As a beginner content negotiation seems to work well.
I have searched for this answer, but can't find an explanation.
ASP.Net Web API in its purest form is intented to create REST ful web services.
As per REST full standards client should have the ability to decide whether the response should be in XML/JSON response. And this can be achieved using Content-negotiation header in the request.
That means your understanding is correct and using Content negotiation you can decide whether you require XML/JSON response in ASP.Net Web API.
If I have to give you example of this then please create web api by default template. This contain value controller.
Now go to chrome browser and request the data and go to IE and request the data. In chrome you will get XML data while in IE you will get JSON data. ( It ask for download json).
Now if you use tool like fiddler and look at request then you will find difference in request header of both browser.
So if you are sure that you always need json data then it is good to return JSON data from controller action it self. If you don't want to do that and still want all your request to be return JSON then please set header "Accept" with application/json.
http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation
In short if you want to your api always communicated by json data then it is good to return result of json type rather then depend on content negotiation.

Django cannot parse POST parameters of WSGIRequest on Internal Server Errors

I'm using Django REST Framework and all the API calls come from Android and iOS apps. The system works perfectly most of the time, however, when an internal server error happens and I get an email from Django, the POST of the WSGIRequest contains <could not parse> instead of the actual posted JSON data (even though 'CONTENT_TYPE': 'application/json' is also in the header, and the data is sent as JSON).
This is really annoying, as it would be great to see the request body that actually causes the error, not just the stacktrace.
The <could not parse> part is very similar to this question (in the ModPythonRequest part): django request.POST contains <could not parse>, except the actual problem is slightly different. Also the reference link in that question (https://stackoverflow.com/questions/12471661/mod-python-could-not-parse-the-django-post-request-for-blackberry-and-some-andro) seems to have gone down, even though the name looked very promising.
I'm on Django 1.6.2 and DRF 2.3.13.
The POST dictionary of the WSGIRequest is always going to be invalid, because it is intended to hold the parsed form data when the Content-Type is application/x-www-form-urlencoded or multipart/form-data.
The data you want is in the body attribute of the WSGIRequest object, which isn't output when that object is converted to a string to be written to the log.
When using Django REST framework, you will typically want to access request.DATA (which will handle whatever formats you have parsers configured for - defaulting to form content and JSON) instead of Django's standard request.POST, which will only handle form encoded data.

How to disable content negotiation and always return JSON from WCF data service?

Let's say I have a northwind database and I use ADO.NET Entity Data Model which I automatically generate from the tables in database. Then I add a new WCF data service that inherits from DataService. When I start the web application, that runs the service I can request data like this:
http://machine/Northwind.svc/Orders
This will return all orders from order table in atom/xml format. The problem is I do not want XML. I want JSON. I think I tried all kinds of settings (web.config) and attributes in my application, but I still get XML. No matter what. I can only get JSON, when I use fiddler and change the request header to accept JSON.
I do not like the concept of content negotiation. I want always to return data in JSON format. How can I achieve that?
Keep in mind that I did not create any model objects, they are automatically created based on database tables and relationships.
Well - content negotiation comes with HTTP. In any case, you could intercept the incoming request and add/overwrite the Accept header to always specify the JSON. There's a sample how to support JSONP which uses a similar trick, I think you should be able to modify it to always return JSON as well. http://archive.msdn.microsoft.com/DataServicesJSONP.
The behavior you criticize is defined by specification of OData protocol. OData defaults to Atom and client can control media type of the representation either by Accept HTTP header or by $format parameter in query string (but I'm not sure if WCF Data services already support this).