简体   繁体   中英

Python - How to make REST POST request

I have implemented a REST service with Java:

@POST
@Path("/policyinjection")
@Produces(MediaType.APPLICATION_JSON) 
public String policyInjection(String request) {

    String queryresult = null;
    String response = null;

    if (request == null) {
        logger.warning("empty request");
    } else {

        //call query() to query redisDB with the request
        queryresult = query(request);

        // call inject() to inject returned policy to floodlight
        response = inject(queryresult);

    }
    return response;
}

But I need to use Python to implement the client to make a POST request to the above service. I am new to python, I want to implement a method do it like this:

def callpolicyInjection():

I'm not sure this is the answer to your exact question, but you should take a look at the requests module.

It allows to send http POST requests (as well as (m)any other http methods) mostly in one line:

>>> import requests

>>> keys = {'username':'Sylvain', 'key':'6846135168464431', 'cmd':'do_something'}
>>> r = requests.post("http://httpbin.org/post",params=keys)

Now, the answer is in the r objects:

>>> print(r)
<Response [200]>

>>> print(r.text)
{
  "origin": "70.57.167.19",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post?cmd=do_something&key=6846135168464431&username=Sylvain",
  "args": {
    "username": "Sylvain",
    "cmd": "do_something",
    "key": "6846135168464431"
  },
  "headers": {
    "Content-Length": "0",
    "Accept-Encoding": "identity, gzip, deflate, compress",
    "Connection": "close",
    "Accept": "*/*",
    "User-Agent": "python-requests/1.2.3 CPython/3.3.1 Linux/3.2.0-0.bpo.4-amd64",
    "Host": "httpbin.org"
  },
  "json": null,
  "data": ""
}

... those are only examples. See requests response content documentation for details.

You can use the requests lib. I won't cover this as it has already been answered.

You can also use urllib and urllib2:

import urllib
import urllib2

data = {
    'user': 'username',
    'pass': 'password'
}

urllib2.urlopen('http://www.example.com/policyinjection/', urllib.urlencode(data))

The secode parameter to urllib2.urlopen is the data to send along with the request. It is optional, but if you use it your request automatically becomes POST. The advantage of urllib over other solutions it that it's part of the standard distribution, so you won't add any extra dependencies to your application.

And if you want performance you should use pycurl :

import pycurl

curl = pycurl.Curl()
curl.setopt(pycurl.URL, 'http://www.example.com/policyinjection/')
curl.setopt(pycurl.POSTFIELDS, 'user=username&pass=password')
curl.perform()

Unfortunately, pycurl is not part of the standard distribution, but you can install it using pip install pycurl or easy_install pycurl .

I have made Nap specifically for this purpose, check it out!

Example usage:

from nap.url import Url
api = Url('http://httpbin.org/')

response = api.post('post', data={'test': 'Test POST'})
print(response.json())

More examples: https://github.com/kimmobrunfeldt/nap#examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM