Example of a POST API Call (Python)

Last updated on
31 August 2018
import requests
import json
import sys
import time
from urllib.parse import urlencode

############################################################
# Helper Functions

def pprint(text):
  s = str(text)
  sys.stdout.write(s + '\n')
  sys.stdout.flush()

def login(auth):
  login = {}
  login['name'] = auth['name']
  login['pass'] = auth['pass']
  l = json.dumps(login)

  req = requests.post(auth['location'], data=l)

  auth['head'] = {}
  auth['cookie'] = {}
  if req.status_code == 200:
    r = json.loads(req.text)
    auth['head']['X-CSRF-Token'] = r['csrf_token']
    auth['head']['Accept'] = 'application/json'
    auth['head']['Content-Type'] = 'application/json'
    auth['cookie'] = req.cookies.get_dict()
    return auth
  else:
    pprint("RemoteConf Login failed. Message from Server:")
    pprint(req.text)
    return False

############################################################
# Script Settings

auth = {}
auth['location'] = "http://example.com/user/login?_format=json"
auth['name'] = "name"
auth['pass'] = "CorrectHorseBatteryStaple"

post_data = {}
post_data['plugin'] = 'asdf'
post_data['actor'] = {'actor_name': 'actor2', 'actor_data':{'this':'that'}}
post_data['action'] = 'test'
post_data['object'] = 'object1'
post_data['data'] = [{'result':'attachment worked', 'type':'spectra_test'},{'result':'duplication worked', 'type':'spectra_test_2'}]
post_data['context'] = 'website1'
post_data['type'] = 'spectra-test'
post_data['time'] = time.time() - 500

get_data = {}

############################################################
# Log in and run test posts

auth = login(auth)

# Test POST
pd = json.dumps(post_data)
pst = requests.post('http://zeomine.local/spectra/post?_format=json', data=pd, headers=auth['head'], cookies=auth['cookie'])
pprint(pst.text)

Help improve this page

Page status: No known problems

You can: