Any idea why I can't POST to this Django REST API? - django

I'm currently trying to get a POST request using multipart/form-data running to the Django REST framework. I've successfully run through some test requests via the interactive API screens, which work fine. I've then tried to convert these over to using a non-Session based auth strategy, and I've consistently got errors. The requests I've sent are of the form:
POST /api/logs/ HTTP/1.1
Host: host:8080
Connection: keep-alive
Content-Length: 258
Accept: application/json
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryTOhRsMbL8ak9EMQB
Authorization: Token -token-
------WebKitFormBoundaryx6ThtBDZxZNUCkKl
Content-Disposition: form-data; name="SubmittedAt"
2014-01-23T10:39:00
------WebKitFormBoundaryx6ThtBDZxZNUCkKl
Content-Disposition: form-data; name="Device"
CheeseDevice
------WebKitFormBoundaryx6ThtBDZxZNUCkKl--
Sadly, the result has been (for all the requests I've run):
{"Device": ["This field is required."], "SubmittedAt": ["This field is required."], "LogFile": ["This field is required."]}
Interestingly, I've been able to send chunks of JSON through to the endpoint, and they're accepted as expected, eg:
POST /api/logs/ HTTP/1.1
Content-Type: application/json
Host: host:8080
Connection: keep-alive
Content-Length: 35
Accept: application/json
Authorization: Token -token-
{
"Device": "CheeseDevice"
}
Returns:
{"SubmittedAt": ["This field is required."], "LogFile": ["This field is required."]}
As expected - it actually accepts the Device argument and only raises errors on the missing items. I'd switch to using JSON, but sadly cannot upload files with it...
Thanks in advance for any help!
Edit:
Further investigation (ie: writing a view method that returns the request data shows that request.DATA isn't getting populated, for some reason. Method I'm using to debug follows:
def test_create(self, request, pk=None):
return Response(request.DATA)
Edit 2:
Even further investigation (and dropping code chunks into the framework for debugging) indicates that the requests are getting caught up in _perform_form_overloading and never hitting the MultiPartParser. Not sure why this is occurring but I'll try and trace it further.

After delving down every level I could find...
Looks like the problem stems from the line endings - ie: the libs and request senders I've been using send the content through with "\n" (LF) endings, while the HTTP spec requires "\r\n" endings (CR,LF)
This hinges on the following code in the Django core, within http/multipartparser.py - in parse_boundary_stream:
header_end = chunk.find(b'\r\n\r\n')
For dev purposes (and because it's going to be way easier to patch at the Django end than in the clients...) I've switched the above line to:
header_end = chunk.replace("\r\n","\n").find(b'\n\n')
This updated code follows the recommendations in Section 19.3 of the HTTP/1.1 spec regarding Tolerant Applications and accepting LF instead of just CRLF - I'll try and get around to seeing if this is suitable for inclusion in the Django core.
Edit:
For reference, the patch is up on GitHub: https://github.com/tr00st/django/commit/9cf6075c113dd27e3743626ab0e18c6616488bd9

This could be due to malformed multipart post data.
Also possible that you don't have MultiPartParser installed, but I don't think that'll be it as you'd normally expect to see a 415 Unsupported Media Type response in that case.

Related

Google Photos REST API "pageSize" and "pageToken" parameters causing 400 Bad Request

I'm trying to get all media items in my Google Photos library and referred following documentation link.
https://developers.google.com/photos/library/guides/list
Documentation says client can request pages using pageSize and provided following example.
GET https://photoslibrary.googleapis.com/v1/mediaItems
Content-type: application/json
Authorization: Bearer OAUTH2_TOKEN
{
"pageSize":"100",
}
i think the comma after 100 is a documentation error and i removed it from request, but whenever i add pageSize (or pageToken) parameter, server always return with 400 Bad Request <p>Your client has issued a malformed or illegal request.<ins>That’s all we know.</ins>
Here are some example REST API calls i tried
GET /v1/mediaItems HTTP/1.1
Host: photoslibrary.googleapis.com
Content-Type: application/json
Authorization: Bearer xxx
{
"pageSize":10
}
GET /v1/mediaItems HTTP/1.1
Host: photoslibrary.googleapis.com
Content-Type: application/json
Authorization: Bearer xxx
{
"pageSize":"10"
}
GET /v1/mediaItems HTTP/1.1
Host: photoslibrary.googleapis.com
Content-Type: application/json
Authorization: Bearer xxx
{
"pageToken":"blha blha"
}
Please note that whenever i removed the json from request body, it start returning 200 OK with predefined pageSize. but i would like to control the pageSize and request next pages using pageToken.
Thanks for any guidance on this matter.
I just started looking at this too. Those parameters shouldn't be passed in the body. They are query parameters. So something like this:
https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100
That worked for me at least. Check out further documentation at https://developers.google.com/photos/library/reference/rest/v1/mediaItems/list to review information about the query parameters.

identifying the proper syntax for using HTTP dataset in ADFv2

I am able to successfully use Postman to authenticate and subsequently get data housed within a sandbox but I cannot figure out how to specify the same data within ADFv2.
I'm expecting to retrieve, temporarily store and later use a bearer token that this API generates. This token is then used in the second step that actually downloads the data I want in JSON format.
For the Authentication step, Postman generates code that looks this:
POST /v1/oauth/token HTTP/1.1
Host: api.sandbox.COMPANY.com
Ocp-Apim-Subscription-Key: MYKEY
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryALPHANUM
cache-control: no-cache
Postman-Token: MYTOKEN
Content-Disposition: form-data; name="key"
MYKEY
Content-Disposition: form-data; name="grant_type"
vapi_key
------WebKitFormBoundaryALPHANUM--
I've created a linked HTTP and REST connection in ADFv2 with the base URL of "https://api.sandbox.COMPANY.com" and using no authentication.
I cannot figure out how to translate the functional Postman connection to a way that ADFv2 will work. Thoughts?
You could check this example.
https://learn.microsoft.com/en-us/azure/data-factory/connector-http#dataset-properties

CSRF exempt on REST View

I am serving an API which will be accessible with a small sensor sending a POST request with data. This sensor has a limited software, and I want to disable the CSRF protection on my API view.
So I've added the decorator:
url(
regex=r'^beacons/$',
view=csrf_exempt(ScanListCreateAPIView.as_view()),
name='beacons'
),
Unfortunately, when I perform a POST with my sensor, I still get a 403 error:
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
<p>You are seeing this message because this HTTPS site requires a 'Referer
header' to be sent by your Web browser, but none was sent
. This header is
required for security reasons, to ensure that your browser is not being
hijacked by third parties.</p>
<p>If you have configured your browser to disable 'Referer' headers, please
re-enable them, at least for this site, or for HTTPS connections, or for
'same-origin' requests.</p>
I've try to add a "Referer: " null header in my POST request, but I still have a 403 response, mentionning that CSRF failed.
My request is:
POST /api/beacons HTTP/1.1
Host: vincent.pythonanywhere.com
Content-Type: application/json
Accept: */*
User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)
Content-Length: 597
{"beacon":"aaa"," ...
The same request passed throught curl is working ok, with a 201 response.
Here is the solution to diable CSRF:
1- As DRF does its own csrf with SessionAuth, you have to specify in the view:
authentication_classes = (BasicAuthentication,)
2- Then I don't know exacly why, but view=csrf_exempt(ScanListCreateAPIView.as_view()), in urls doesn't work. Instead, use the braces mixin:
from braces.views import LoginRequiredMixin, CsrfExemptMixin
class ScanListCreateAPIView(ListCreateAPIView, CsrfExemptMixin):
authentication_classes = (BasicAuthentication,)

Amazon SES Sending email with attachments

I am trying to send mails with attachment by using Amazon SES
HttpRequest httpReq = new HttpRequest();
httpReq.setMethod('POST');
httpReq.setEndpoint('https://email.us-east-1.amazonaws.com');
Blob bsig = Crypto.generateMac('HmacSHA256', Blob.valueOf(awsFormattedNow), Blob.valueOf(secret));
httpReq.setHeader('X-Amzn-Authorization','AWS3-HTTPS AWSAccessKeyId='+key+', Algorithm=HmacSHA256, Signature='+EncodingUtil.base64Encode(bsig));
httpReq.setHeader('Date',awsFormattedNow);
httpReq.setHeader('From','sample#gmail.com');
httpReq.setHeader('To','sample#gmail.com');
httpReq.setHeader('Subject','Hello');
httpReq.setHeader('Accept-Language','en-US');
httpReq.setHeader('Content-Language','en-US');
httpReq.setHeader('Content-Type','multipart/mixed;boundary=\"_003_97DCB304C5294779BEBCFC8357FCC4D2\"');
httpReq.setHeader('MIME-Version','1.0');
// httpReq.setHeader('Action','SendRawEmail');
String email = 'Action=SendRawEmail';
email += '--_003_97DCB304C5294779BEBCFC8357FCC4D2 \n Content-Type: text/plain; charset="us-ascii" \n Content-Transfer-Encoding: quoted-printable \n';
email +='Hi Andrew. Here are the customer service names and telephone numbers I promised you.';
httpReq.setBody(email);
System.debug(httpReq.getBody());
Http http = new Http();
HttpResponse response = http.send(httpReq);
I am getting error like
<AccessDeniedException>
<Message>Unable to determine service/operation name to be authorized</Message>
</AccessDeniedException>
Kindly please help me where i am doing wrong .Thanks in advance
Take another look at the documentation. There are several issues with your code.
SES expects an HTTP POST with all of the parameters strung together consistent with application/x-www-form-urlencoded POST requests.
Your HTTP request needs to be Content-type: application/x-www-form-urlencoded, not multipart/mixed... -- that's part of the raw message you're trying to send.
You are mixing up things that should be in the body, and setting HTTP request headers, instead. For example, these are also incorrect:
httpReq.setHeader('From','sample#gmail.com');
httpReq.setHeader('To','sample#gmail.com');
httpReq.setHeader('Subject','Hello');
These should go in the request body, not in the HTTP request headers. Also, the values are urlencoded. From the example code:
Action=SendEmail
&Source=user%40example.com
&Destination.ToAddresses.member.1=allan%40example.com
The line breaks were added for clarity.
Your interests might be best served by trying to successfully send a simple e-mail, first, and then later attempting to modify your code to support attachments, because you have numerous errors that will need to be corrected before this code will work properly.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/query-interface-requests.html
http://docs.aws.amazon.com/ses/latest/APIReference/API_SendRawEmail.html

Make multipart/form-data request with json

I am calling a web service from Classic ASP/VBScript. The call expects 3 parameters, 1 which is form data and 2 which are optional file data. Currently not sending the file data.
The form data is multiple fields, wrapped up in json.
So I'm setting the content-type on the ServerXMLHTTP object to be multipart/form-data, and I'm creating the json segment as such and sending it as the data
Content-Type: application/json; charset=utf-8
{
"Token": "...",
"FirstName": "First Name",
I keep getting Request must be Content-type: multipart/form-data.
I've tried adding a boundary and same thing.
I know I can do this in C# using MultipartFormDataContent, but it has to be Classic unfortunately.
What's the correct way to send? Thanks!