How to use the BonitaSoft REST API from Python/Django

1
0
-1

How do you use the BonitaSoft REST API from Python/Django?

Comments

Submitted by 13509055 on Tue, 02/04/2014 - 02:59

It's not a question... It's a tutorial... you should write it in the tutorial section or something

Submitted by ttoine on Tue, 02/04/2014 - 12:26

What I would recommand, is to just write a short question about the topic of this howto, and to write the howto itself in an answer. This is the way it should be done also on Stackoverflow, where this howto has been posted first. As Bonita community manager, I really enjoy to see members of the community sharing their knowledge. Thank you very very much for you time, jfmcgrath.

Submitted by jfmcgrath on Tue, 02/04/2014 - 15:51

I've changed it to a Q&A.

Submitted by ttoine on Tue, 02/04/2014 - 15:53

Yeah !!!! thank you very much !

1 answer

1
0
-1

I couldn't find much information online about how to do this, so I decided to post how I did it. Please feel free to share your suggestions or experiences.

First off, in settings.py, I set a few variables that I could reuse. These are the defaults if you are using the Bonita Studio locally.

  1. BPM_HOST = 'http://localhost:9090/bonita-server-rest/'
  2. BPM_USERNAME = 'restuser'
  3. BPM_PASSWORD = 'restbpm'

In views.py, I set up a function that I could use anytime I needed to do a call. It uses the variables from the settings file and accepts parameters for logged in user, url to call and a dictionary of post_data. It sets the Basic auth and content type headers the way Bonitasoft expects.

  1. from django.conf import settings
  2. import urllib
  3. import urllib2
  4. import base64
  5.  
  6. def restcall(user,url,post_data={}):
  7. #create bpm_request
  8. bpm_request = urllib2.Request(settings.BPM_HOST + url)
  9.  
  10. #encode username and password and add to header
  11. authKey = base64.b64encode(settings.BPM_USERNAME + ':' + settings.BPM_PASSWORD)
  12. bpm_request.add_header("Authorization","Basic " + authKey)
  13.  
  14. #add content type to header
  15. bpm_request.add_header("Content-Type","application/x-www-form-urlencoded")
  16.  
  17. #must send current user in options
  18. current_user = 'user:' + ‘user'
  19. post_data['options'] = current_user
  20.  
  21. bpm_request.add_data(urllib.urlencode(post_data))
  22.  
  23. response = urllib2.urlopen(bpm_request)
  24.  
  25. try:
  26. return response
  27. except Exception, exception:
  28. logging.info(str(exception))
  29. #endtry
  30. #end restcall

Now say you wanted to build a list of all your Process Instances:

  1. import xml.etree.ElementTree as ET
  2. response = restcall(my_user,'API/queryRuntimeAPI/getLightProcessInstances')
  3. root = ET.parse(response).getroot()
  4. UUIDs=[]
  5. for doc in root.findall('LightProcessInstance'):
  6. UUIDs.append(doc.find('instanceUUID').find('value').text)
  7. #endfor

Or to build a list of Process Instances that would be in your inbox:

  1. response = restcall(my_user,'API/queryRuntimeAPI/getLightParentProcessInstancesWithActiveUser/' + my_user +'?fromIndex=0&pageSize=200')
  2. root = ET.parse(response).getroot()
  3.  
  4. UUIDs=[]
  5. for doc in root.findall('LightProcessInstance'):
  6. UUIDs.append(doc.find('instanceUUID').find('value').text)
  7. #endfor

Posting data is a real pain. First off, I created a function to clean any text you might send:

  1. def super_clean(text):
  2. """This will make data safe to send by rest.
  3. Escape for <> (so we don't screw up our XML).
  4. Quote plus to handle + signs.
  5. Encode for international chars and smart quoates.
  6. Strip to take out extra blanks before and after"""
  7. return urllib.quote_plus(escape(text.encode('utf-8','replace').strip()))
  8. #end super_clean

And here's how I generated the XML map. In case you missed it, the documentation for the XML map is at in their docs.

  1. variable_string = '<map>' + \
  2. '<entry><string>billing_department</string><string>' + super_clean(form.cleaned_data['billing_department']) + '</string></entry>' + \
  3. '<entry><string>amount</string><double>' + super_clean(str(form.cleaned_data['amount'])) + '</double></entry>' + \
  4. '<entry><string>account</string><string>' + super_clean(str(form.cleaned_data['number_attended'])) + '</long></entry>' + \
  5.  
  6. variable_string += '<entry><string>participant_name</string><list>'
  7. for tempform in participant_formset.forms:
  8. if 'participant_name' in tempform.cleaned_data:
  9. variable_string += '<string>' + super_clean(tempform.cleaned_data['participant_name']) + '</string>'
  10. #endif
  11. #endfor
  12. variable_string += '</list></entry>'
  13.  
  14. post_data = {}
  15. post_data['variables'] = variable_string

And you update an existing record with:

  1. process_instance_uuid = form.cleaned_data['uuid']
  2. response = restcall(request,'API/runtimeAPI/setProcessInstanceVariables/' + process_instance_uuid,post_data)

Part 2 - Adding Attachments

Attaching a file requires a call to /API/runtimeAPI/addAttachmentOctetStream/{instanceUUID}?name=�&fileName=�

This REST call is a little different than a regular Bonita Rest call, so I wrote the following function to help:

  1. from django.conf import settings
  2. import urllib
  3. import urllib2
  4. import base64
  5.  
  6. def restAttachment(user,url,file):
  7. #create bpm_request
  8. bpm_request = urllib2.Request(settings.BPM_HOST + url,data=file.read())
  9.  
  10. #encode username and password and add to header
  11. authKey = base64.b64encode(settings.BPM_USERNAME + ':' + settings.BPM_PASSWORD)
  12. bpm_request.add_header("Authorization","Basic " + authKey)
  13.  
  14. #must send current user in options
  15. current_user = 'user:' + 'user'
  16.  
  17. #add headers
  18. bpm_request.add_header("Content-Type","application/octet-stream")
  19. bpm_request.add_header('Content-Length', str(file.size))
  20. bpm_request.add_header('Cache-Control', 'no-cache')
  21. bpm_request.add_header('options', current_user)
  22. bpm_request.add_header("Content-Disposition","attachment; filename="+urllib.quote(file.name))
  23.  
  24. try:
  25. response = urllib2.urlopen(bpm_request)
  26. except Exception, exception:
  27. logging.info(str(exception))
  28. #endtry
  29.  
  30. return response
  31. #end restAttachment

In forms.py, you need a form like this one:

  1. class AddAttachmentForm(Form):
  2. process_instance_uuid = CharField(widget=HiddenInput())
  3. attachment = FileField()
  4. #end AddAttachmentForm

In your template, you need to have the following (note the enctype):

  1. <form method="post" enctype="multipart/form-data" action="add_attachment"> {% csrf_token %}
  2. {{ add_attachment_form }}
  3. <input type="submit" value="Upload Attachment" />
  4. </form>

In views.py, when building the above template, you should have something like:

add_attachment_form = AddAttachmentForm(initial={'process_instance_uuid':my_uuid,})

When processing the form, you should have:

  1. if 'attachment' not in request.FILES:
  2. return render_to_response(...
  3.  
  4. form = AddAttachmentForm(request.POST, request.FILES) #note the request.FILES
  5. response = restAttachment(user,'API/runtimeAPI/addAttachmentOctetStream/' + form.cleaned_data['process_instance_uuid'] + '?name=bonita_attachment_type_field_name) + '&fileName=' + urllib.quote(request.FILES['attachment'].name),request.FILES['attachment'])

Part 3 - Using the Search Bonitasoft’s search function via REST Call

As far as I can tell, there is little-to-no documentation on this.

Let’s start with the basics. To do a search, you have to post to API/queryRuntimeAPI/searchByMaxResult?firstResult=�&maxResults=�. If you post to API/queryRuntimeAPI/search, you only get the number of records, not the records themselves.

You can use firstResult and maxResults for paging.

Your body should look like:

options=user:my_user&query=<query_xml>

The hard part is figuring out what goes in the query_xml. The examples I found on the Bonitasoft site were full of br tags. For some reason, the Bonitasoft site stripped out their xml tags. The query xml can be created using the Java API. One way is to use the Groovy Editor in the Bonita Studio and run it with the Evaluate button. In the following example, “first_name” is one of the data fields I created.

  1. import org.ow2.bonita.search.SearchQueryBuilder;
  2. import org.ow2.bonita.search.index.ProcessInstanceIndex;
  3. import org.ow2.bonita.search.index.ActivityInstanceIndex;
  4.  
  5. SearchQueryBuilder query = new SearchQueryBuilder(new ProcessInstanceIndex());
  6. query.criterion(ProcessInstanceIndex.VARIABLE_NAME).equalsTo("first_name").and().criterion(ProcessInstanceIndex.VARIABLE_VALUE).equalsTo('Archibald');
  7. return query;

You would think that this would return any record where the field “first_name” is set to “Archibald”. In fact it returns any record that includes the field “first_name” (which should be all of them) and has any user defined field that has a value of “Archibald”. So if someone’s last name is “Archibald”, they would be returned as well. There doesn’t appear to be a way around this. It’s probably best just to embrace the fact that it’s a full search and simplify it to:

query.criterion(ProcessInstanceIndex.VARIABLE_VALUE).equalsTo('Archibald');

Which generates the following XML:

  1. <SearchQueryBuilder>
  2. <index class="org.ow2.bonita.search.index.ProcessInstanceIndex"/>
  3. <query>
  4. <org.ow2.bonita.search.Criterion>
  5. <builder reference="../../.."/>
  6. <fieldName>variable_value</fieldName>
  7. <value>Archibald</value>
  8. </org.ow2.bonita.search.Criterion>
  9. </query>
  10. </SearchQueryBuilder>

Again, this only searches user defined fields. If you want to search other fields, seehttp://documentation.bonitasoft.com/javadoc/bpm_engine/5.9/org/ow2/bonita/search/index/ProcessInstanceIndex.html. I also wanted to search the creator, so my XML became:

  1. <SearchQueryBuilder>
  2. <index class="org.ow2.bonita.search.index.ProcessInstanceIndex"/>
  3. <query>
  4. <org.ow2.bonita.search.Criterion>
  5. <builder reference="../../.."/>
  6. <fieldName>variable_value</fieldName>
  7. <value>Archibald</value>
  8. </org.ow2.bonita.search.Criterion>
  9. <string> OR </string>
  10. <org.ow2.bonita.search.Criterion>
  11. <builder reference="../../.."/>
  12. <fieldName>startedBy</fieldName>
  13. <value>Archibald</value>
  14. </org.ow2.bonita.search.Criterion>
  15. </query>
  16. </SearchQueryBuilder>

Lastly, I wanted to limit my search to a date range. The format for dates is yyyymmddhhmmssttt. I want to search for a date range, so I’m setting the start time to 0 and the end time to all 9s. Logic dictates that I add parenthesis around the OR clause.

  1. <SearchQueryBuilder>
  2. <index class="org.ow2.bonita.search.index.ProcessInstanceIndex"/>
  3. <query>
  4. <string>(</string>
  5. <org.ow2.bonita.search.Criterion>
  6. <builder reference="../../.."/>
  7. <fieldName>variable_value</fieldName>
  8. <value>Archibald</value>
  9. </org.ow2.bonita.search.Criterion>
  10. <string> OR </string>
  11. <org.ow2.bonita.search.Criterion>
  12. <builder reference="../../.."/>
  13. <fieldName>startedBy</fieldName>
  14. <value>Archibald</value>
  15. </org.ow2.bonita.search.Criterion>
  16. <string>)</string>
  17. <string> AND </string>
  18. <org.ow2.bonita.search.Criterion>
  19. <builder reference="../../.."/>
  20. <fieldName>startedDate</fieldName>
  21. <value>[20130101000000000 TO 20131231999999999]</value>
  22. </org.ow2.bonita.search.Criterion>
  23. </query>
  24. </SearchQueryBuilder>

So now that I have my XML, I just need to plug it into Python. I created a form:

  1. class SearchForm(Form):
  2. search_text = CharField(widget=TextInput(attrs={'size':'80'}))
  3. start_date = DateField(widget=widgets.TextInput(attrs={"class":"calendar"}))
  4. end_date = DateField(widget=widgets.TextInput(attrs={"class":"calendar"}))

I didn't want to mess with paging, so if there are more than 100 records, I give them a message to narrow their criteria. Notice that in my xml I put quotes around my search text. That makes the search match the whole text. If there is a space in the text and you don't use quotes, the search doesn't try to match all the words. Here's how I process the form and execute the search:

  1. if request.method == 'POST':
  2. search_form = SearchForm(request.POST)
  3.  
  4. if not search_form.is_valid():
  5. return render_to_response(...
  6.  
  7. #format dates in manner expected by API
  8. start = search_form.cleaned_data['start_date'].strftime('%Y%m%d') + "000000000"
  9. end = search_form.cleaned_data['end_date'].strftime('%Y%m%d') + "999999999"
  10.  
  11. post_data={}
  12. #the search query must be in this xml format
  13. post_data['query'] = '''
  14. <SearchQueryBuilder>
  15. <index class="org.ow2.bonita.search.index.ProcessInstanceIndex"/>
  16. <query>
  17. <string>(</string>
  18. <org.ow2.bonita.search.Criterion>
  19. <builder reference="../../.."/>
  20. <fieldName>variable_value</fieldName>
  21. <value>"%s"</value>
  22. </org.ow2.bonita.search.Criterion>
  23. <string> OR </string>
  24. <org.ow2.bonita.search.Criterion>
  25. <builder reference="../../.."/>
  26. <fieldName>startedBy</fieldName>
  27. <value>"%s"</value>
  28. </org.ow2.bonita.search.Criterion>
  29. <string>)</string>
  30. <string> AND </string>
  31. <org.ow2.bonita.search.Criterion>
  32. <builder reference="../../.."/>
  33. <fieldName>startedDate</fieldName>
  34. <value>[%s TO %s]</value>
  35. </org.ow2.bonita.search.Criterion>
  36. </query>
  37. </SearchQueryBuilder>''' \
  38. % (super_clean(search_form.cleaned_data['search_text']),
  39. super_clean(search_form.cleaned_data['search_text']),
  40. start,
  41. end)
  42.  
  43. #get number of records
  44. response = restcall(request,'API/queryRuntimeAPI/search',post_data)
  45. number_of_records = response.read()
  46. if is_int(number_of_records):
  47. number_of_records = int(number_of_records)
  48. else:
  49. return render_to_response(...
  50.  
  51. if number_of_records > 100:
  52. return render_to_response(...
  53.  
  54. if number_of_records == 0:
  55. return render_to_response(...
  56.  
  57. #now get the records
  58. response = restcall(request,'API/queryRuntimeAPI/searchByMaxResult?firstResult=0&maxResults=100',post_data)
  59. root = ET.parse(response).getroot()
  60.  
  61. #loop through requests
  62. for doc in root.findall('LightProcessInstance'):
  63. ...

Notifications