Code Samples

This section presents basic work flow of polling events from the Firehose API.

We are going to implement the following algorithm:

  • every five seconds check if there are any new events in the Firehosedealstream
  • if there are any events, iterate until you read all the pages of events available, i.e. until we reach the top of the stream
  • for every event print out the current deal's data and the information about what has changed

Here is a simple Python script that presents the idea:

             
importrequestsimportjsonimporttime# your oauth tokentoken="2124…"# main poll loop - check for new events every 5 secondsstartingPosition='top'whileTrue:# loop to recieve all pages of events since we checked last timeonTop=FalsewhilenotonTop:print'Polling...'url="https://api.getbase.com/v3/deals/stream"response=requests.get(url,params={'position':startingPosition},headers={'Authorization':“不记名{}”.format(token)})ifresponse.status_code!=200:raiseException('Request failed with {}'.format(response.status_code))# iterate through events and print themforiteminresponse.json()['items']:print("Deal data:\n{}".format(json.dumps(item['data'],indent=4)));ifitem['meta']['event_type']=='updated':print("Updated: {}".format(item['meta']['previous'].keys()))print(“旧价值观:\ n {}".format(json.dumps(item['meta']['previous'],indent=4)));# check if we have reached the top of the streamonTop=response.json()['meta']['top']# prepare the position for the next requeststartingPosition=response.json()['meta']['position']print"Sleeping..."time.sleep(5)

Now if this script is run it starts to poll the events from Firehose API. When any deal gets updated, e.g. through a web frontend, you should see the output similar to the one below:

             
Polling...Deal data:{"last_stage_change_by_id":1212137,"stage_id":6961518,"name":"Website Redesign","tags":[],"customized_win_likelihood":null,"created_at":“2017 - 07 - 05 - t17:20:52z”,"dropbox_email":"[email protected]","contact_id":174841170,"id":39912342,"organization_id":null,"currency":"USD","hot":false,"value":"100.00","custom_field_values":[],"creator_id":1212137,"loss_reason_id":null,"source_id":null,"last_stage_change_at":“2017 - 07 - 05 - t17:20:52z”,"estimated_close_date":null,"owner_id":1212137}Updated:[u'name',u'value']Old values:{"name":"Website","value":"50.00"}Sleeping...

Refer to the Firehose API resources to see what resources are currently streamed through the Firehose API.