PUT, GET ,POST ,DELETE methods using djangorest framework - django

I'm using django rest framework , I use the post and get methods and it works, but I didn't understand how to use PUT and DELETE, do I use it in the html forms like : method='PUT' ? but i read that the browsers assimilated it to a GET method , do I write fonctions in my code for PUT and DELETE??
-I read many articles about rest and restful and I didn't understand the difference between it some people says that its the same , and others no but dont clarify,when I use POST and GET can I say that it's RESTFUL
thank you

Unless there's been a recent development, HTML forms do not support PUT nor DELETE methods. (GET, POST, PUT, and DELETE methods are part of HTTP, not HTML, more on this topic in this question)
However you can send PUT and DELETE requests using an HTTP client, e.g. Python has a library called requests you can use to send requests. Or if you want to do so from the front-end, e.g. from a browser, you can use JavaScript lib capable of sending out HTTP requests (or the more recent fetch() that comes with modern browsers, or its polyfill for older browsers)
e.g.
>>> import requests
>>> req = requests.request('PUT', 'http://yourapi/resource')
<Response [200]>

Related

Django URLs: URL Issues [duplicate]

Is there a way to check if a request is AJAX in Python?
The equivalent of PHP's $_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest'?
If the AJAX framework sets the X-Requested-With header in its requests, then you will be able to use that header to detect AJAX calls. It's up to the client-side framework to do this.
Getting hold of the HTTP headers depends on your Python framework of choice. In Django, the request object has an is_ajax method you can use directly.
is_ajax() is deprecated since Django 3.1 (as of 28th May, 2021) as they stated that it depends on jQuery ways of sending request but since people use fetch method a lot to make call Ajax calls, it has become unreliable in many cases.
Usually, text/html is requested in the header in the first option in the browser when it just the loads the page. However, if you were making API call, then it would become */* by default, if you attach Accept: application/json in the headers, then it become
application/json
So, you can check easily if the request is coming from ajax by this
import re # make sure to import this module at the top
in your function
requested_html = re.search(r'^text/html', request.META.get('HTTP_ACCEPT'))
if not requested_html:
# ajax request it is
Check this how to check if request is ajax in turbogears
also this for how to do this in Django(it depends in your framework): How to check contents of incoming HTTP header request
Just in case someone can find this useful, the Sec-Fetch-Dest can hint if the request is an ajax call or not.
So one could have something like this:
is_ajax_call = all(
request.headers.get("Sec-Fetch-Dest", "")
not in secFetchDest for secFetchDest in ["document", "iframe"]
)

Make multiple rest get requests and save output

I need to call a REST-ful webservice in using a GET method with some parameters and save the output of the same.
My first approach was to make some requests in JavaScript and log the output using console.log(), but the server doesn't allow CORS. So I can't make it that way.
I am pretty sure this might be a common thing but I can't seem to find a simple way to do it. What would be the simplest way to do it? Is there any software that would allow me to make an array, let's say with 100 parameters, save 100 calls or what would be a better way to do it? PHP script?
p.s. I can't activate CORS in the server, nor can I place code in the same domain. So far I have an example I can call in the browser and have the XML return.
As far as CORS is concerned, that has to do with the API you're running on not allowing requests to be made from a different domain. This could be fixed by allowing CORS in the API you are developing on.
CORS Link: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
The other option would be to have your website on the same domain as the API.
Once you have done that, you can simply make multiple AJAX requests to the API.
AJAX HTTP GET example: HTTP GET request in JavaScript?
EDIT:
You might also have to enable CORS in the HTTP header of your request. This would have to be added to an AJAX request:
Access-Control-Request-Headers: x-requested-with
Here is a helpful link for jquery in particular: How to get a cross-origin resource sharing (CORS) post request working

using httplib2 Python to create REST POST listener

I found woefully few samples of httplib2 using the following template defined in the httplib2 documents.
The following (GETs) work (and I now need to implement POST methods using it)
URLS = (
'/', 'PingLocal',
'/ping', 'PingLocal',
'/ping/silo', 'PingSilo'
)
class PingLocal(object):
def GET(self):
return json.dumps({'time': time.strftime('%m/%d/%Y %I:%M:%S'), 'message': 'XYZ Server Responding to Ping'})
How to implement POST methods and pass data (body) to the post request?
A few examples I did come across do not use this suggested
"URLS-list / Classes" model.
Any pointers appreciated. Thank you.
I made a mistake.
In the code I am implementing the REST Server AND in the implemented methods - I am in turn making REST client calls to remote URIs.
I am using httplib2 to make those REST client calls (as the library documentation clearly mentions - its the client library).
I am in turn using web.py module to implement the REST server - and found the relevant documentation there.
Thank you

Difference between REST call and URL

I have been into web development from sometime. But recently came across an old technology, REST. I read various places about REST calls, what I have understood about REST service is,
REST service responds back with JSON or XML data, which can be used on client side for rendering the DOM elements.
It enhances the use of HTTP protocol.
The URL difference between a REST call and normal URL is:
REST CALL: wwww.xyz.com/getCart/12
URL: wwww.xyz.com/getCart.php?cartId=12
I got the basic difference, hitting the URL would render a page at the server end and would return the response, whereas making an AJAX Call to the REST service would simply return a JSON or a XML output which can be parsed at the client end.
My question is:
If I make my .php page to render a JSON string, and the application makes a AJAX call to the php page to get the JSON response back and use it on client side to render the DOM, then what is the difference between REST call and a normal URL call.?
How REST calls are configured differently from normal URLs?
There's a lot of misinformation and confusion about REST. I'm not surprised that these three points are what you understood from the information available, but they are wrong.
REST isn't coupled to any particular data format or media type. The most important constraint in REST is the emphasis on an uniform interface, which means in this case that the server should be able to respond with whatever data format or media type the clients accept. Under HTTP, the client will tell what formats it can understand through the Accept header, and the server should comply or fail with a 406 Not Acceptable error.
In the same way, REST isn't coupled to any particular protocol, although it's often convoluted with HTTP. Again, following the uniform interface, the clients should be able to follow any links provided by the server, for any protocol with a valid URI scheme.
The semantics of URLs are completely irrelevant to REST. All that matters to REST is that an URL identifies one and only one resource. The URL is an atomic identifier and the client shouldn't rely on any semantics embedded in it for any operations. The two examples you give are both valid in REST. There's nothing more or less RESTful about any of them.
To answer your question, under a REST application the difference you imagine doesn't exist. Hitting an URL will return a response. If the client is requesting with an Accept: text/html header, it may return the human-friendly html page to be rendered by a browser. If the client requests with an Accept: application/json or Accept: application/xml, it may return a machine-friendly format to be read by another application.
REST is just an architectural style, there is no technical difference.
One of the things that REST defines is that your URL needs to be atomic identifiers that refer to only one resource.
GET /users/:id (return the user with the given :id)
PUT /users/:id (update the user with the given :id)
Here is an answer about using a framework to make a REST API in php.
Rest puts more emphasis on the verbs, like GET, PUT, POST... You can call one method like
/api/Customers
and depending on the verb you use it will do a get, post, put or delete. You can also make more easy URL's like
/api/Customers/{id}/Orders/{id}
instead of making a method that would be
api/GetCustomersOrders?id=x&id=y.
All Web Services are APIs, but not all APIs are Web services.
APIs are application interfaces, meaning that one application is able to interact with another application in a standardized way.
Web services are a type of API, which must be accessed through a network connection.
REST APIs are a standardized architecture for building web APIs using HTTP methods.

Using Request, HttpNtlmAuth to make a system call with authentication

I've got the following snip of code the has the audacity to tell me it is "FAIL to load undefnied" (the nerve...) I'm trying to pass my authenticated session to a system call that uses javascript.
import requests
from requests_ntlm import HttpNtlmAuth
from subprocess import call
# THIS WORKS - 200 returned
s = requests.Session()
r = s.get("http://example.com",auth=HttpNtlmAuth('domain\MyUserName','password'))
call(["phantomjs", "yslow.js", r.url])
The issue is when "calL" gets called - all I get is the following
FAIL to load undefined.
Im guessing that just passing the correct authenticated session should work - but the question is how do I do it such that I can extract the info I want. Out of all the other attempts this has been the most fruitful. Please help - thanks!
There seem to be couple things going on here so I'll address them one-by-one.
The subprocess module in python is meant to be used to call out to the system as if you were using the command line. It knows nothing of "authenticated session"s and the command line (or shell) has no knowledge of how to use a python object, like a session, to work with phantomjs.
phantomjs has python bindings since version 1.8 so I would expect this might be made easier by using them. I have not used them, however, so I can not tell you with certainty that they will be helpful.
I looked at yslow's website and there appears to be no way to pass it the content that you are downloading with requests. Even then, the content would not have everything (for example: any externally hosted javascript that would be loaded by selenium/phantomjs or a browser, is not loaded by requests)
yslow seems as though it normally just downloads the URL for you and performs its analysis. When the website is behind NTLM, however, it first sends the client a 401 response which should indicate to the client that it must authenticate. Further, information is sent to the client that tells it how to authenticate and provides it parameters to use when authenticating for NTLM. This is how requests_ntlm works with requests. The first request is made and generates a 401 response, then the authentication handler generates the proper header(s) and re-sends the request which is why you see the 200 response bound to r.
yslow accepts a JSON representation of the headers you want to send so you can try to use the headers found in r.request.headers but I doubt they will work.
In short, this is not a question that the people who normally follow the requests tag can help you with. And looking at the documentation for yslow it seems that it (technically) does not support authentication of any type. yslow developers might argue though that it supports Basic Authentication because it allows you to specify headers.