Endpoint for creating new user in python using Elasticsearch client

I am trying to create a new user by API in flask

@app.route('/create-new-user', methods=['GET','POST'])
def createUser():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('email')
        fullname = request.form.get('fullname')
        role = request.form.getlist('role')
        body ={"password":password, "username":username, "email":email, "fullname":fullname, "role":role}
        uri = f'https://localhost:9200/_security/user/{username}'
        es = Elasticsearch(hosts=uri, basic_auth=('elastic', 'zoU_Ec8JjbPnQNG4b8kY'), ca_certs="872ee6c0879fc0cfe73054c3ba7afb5902dbb171a2c215af35a5faab1206b924", verify_certs=False)
        return f'{es.info()}'
    return render_template('add_user.html')

But I don't understand how to pass the submitted data to this localhost:9200/security/user/new-user-username URL , using documentation create or update a user api but it's working fine in Dev tools don't know how to convert that into python

I also looked into put_user method in ElasticSearch.client.SecurityClient but unable to get it how to use or implement in my code

Hello! If I'm understanding correctly, it sounds like you're saying there is no method on the Elasticsearch interface to pass the arguments to?

You can use the Transport class to access lower-level APIs Connection Layer API — Elasticsearch 7.16.0 documentation

Also make sure that you are correctly passing the host to the Elasticsearach class. You are passing the route to security as the host (see API Documentation — Elasticsearch 7.16.0 documentation).

1 Like

Thanks, @JLeysens I did try to use the perform_request method I was getting an issue
when setting the headers keyword argument I did try

headers = {'content-type':'application/json'}
headers = {'content-type':'application/mapbox-vector-tile'}
headers = {'content-type':'text/plain'}

but put_user helped me out to create a user, update user, and many more

Here is a code Example what I did is I just pass instance of ElasticSearch into the SecurityClient

Edited Simple and better solution

body ={"password":password, "username":username, "email":email, "full_name":fullname, 'enabled':True, 'roles':role}
uri = f'https://localhost:9200/'
client = Elasticsearch(hosts=uri, basic_auth=(ELASTIC_USER, 'ELASTIC_PASS'), ca_certs=CERTIFICATE, verify_certs=False)
client.perform_request(body=body, method='POST', path=f'/_security/user/{username}', headers={'content-type':'application/json', 'accept':'application/json'})
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.