how to use the curl POST function in Linux terminal to create a document in python

413 views Asked by At

Am trying to add a new record into a python document and I think am stuck with an issue caused by the curl post function. I have attached the python file and the error received when posting to my url. Could anyone kindly point me towards the right direction.

I dont understand the error code to identify whether the problem comes from the python code bu I do suspect an issue with the curl url.

#!/usr/bin/python
import json
from bson import json_util
from bson.json_util import dumps
import bottle
from bottle import route, run, request, abort
#imports for database
from pymongo import MongoClient
connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']

# set up URI paths for REST service
@route('/hello', method='GET')
def get_hello():
    word = '"'+request.GET.get('name', None)+'"'
    string="{hello:"+word+"}"
    return json.loads(json.dumps(string, indent=4, default=json_util.default))

@route('/strings', method='POST')
def run_post():
    first = '"'+request.json.get('string1')+'"'
    second = '"'+request.json.get('string2')+'"'
    data="{first:"+first+",second:"+ second+"}"
    return json.loads(json.dumps(data, indent=4, default=json_util.default))


@route('/create', method='POST')
def run_create(): 
    myid = request.json.get('id')
    print(myid)
    cert_number = request.json.get('certificate_number')
    bus_name = request.json.get('business_name')
    date = request.json.get('date')
    result = request.json.get('result')
    sector = request.json.get('sector')
    added_id = collection.insert({"id":myid,"certificate_number":cert_number,"business_name":bus_name,"date":date,"result":result,"sector":sector})
    added_doc = collection.find_one({"_id":added_id})
    return json.loads(json.dumps(added_doc, indent=4, default=json_util.default))

#url does not allow spacing when passing an argument,
#therefore i use underscores when passing the business_name and the remove them
#when creating the query
@route('/read', method='GET')
def get_read():
    word = request.params.get('business_name')
    word = word.replace("_"," ")
    found_doc = collection.find({"business_name":{'$regex':word}}) #will still get results when user pass parameter with white space
    return dumps(found_doc)

@route('/update', method='GET')
def get_update(rslt = "Violation Issued"):
    myid = request.query.id
    query = { "id" :myid}
    new_update =  { "$set":{"result":rslt}}
    collection.update_one(query,new_update)
    updated_doc = collection.find_one({"id":myid})
    return json.loads(json.dumps(updated_doc, indent=4, default=json_util.default))

@route('/delete', method='GET')
def get_update():
    myid = request.query.id
    query = {"id" :myid};
    print(query)
    result = collection.delete_one(query)
    return "document with id "+myid+" Has beed deleted from the City Collection"



if __name__ == '__main__':
    run(debug=True,reloader = True)
    #run(host='localhost', port=8080)

Error: post curl url

Returned HTML: post terminal error

python error: error on run terminal

2

There are 2 answers

0
Jakob F On BEST ANSWER

The Problem is that at one point in the json in your curl request you used instead of ". Therefore the json parser throws an error.

So instead of

"business_name" : “ACME Test INC."

write:

"business_name" : "ACME Test INC."
0
Etra On

Not sure if you solved this but here we go. Jakob was correct that you used instead of " Next, get the values from the document you are inserting

data = request.json (Contains parsed content)

Assign a value to the variables you need such as id

id = data['id']

Store all the values in a dictionary variable (I think it is much cleaner this way)

document = {"id":myid,"certificate_number":cert_number,"business_name":bus_name,"date":date,"result":result,"sector":sector}

Lastly, use insert_one and catch errors

try:
    collection.insert_one(document)
    print("CREATED NEW DOCUMENT")

except Exception as e:
    print("ERROR: ", e)

Also, there are several ways to fix the "space" problem you mention for cURL requests. One way is to simply add a %20 between spaces like so:

ACME%20TEST%20INC.

I hope that helps.