Package: bmaclient
bmaclientbmaclient is official BPPTKG Monitoring APIs (BMA) Python client. It can be used
to fetch various monitoring data from BMA web services using Python.InstallationInstall from PyPI by typing this command:pip install -U bmaclientMaking RequestsYou must set valid API key or OAuth2 access token to make authenticated request.
For example, using API key:frombmaclientimportMonitoringAPIapi=MonitoringAPI(api_key='API_KEY')data=api.fetch_bulletin()print(data)Or using access token:frombmaclientimportMonitoringAPIapi=MonitoringAPI(access_token='ACCESS_TOKEN')data=api.fetch_bulletin()print(data)Using API key is only suitable for read only request. If you want to modify
server resources, it'srecommendedto use OAuth2 access token.You can apply field lookup filtering by passing keyword arguments:data=api.fetch_bulletin(eventdate__gte='2019-07-01 12:24:00',eventdate__lt='2019-07-11 13:14:00',eventtype='MP',nolimit=True)print(data)For the APIs that require parameters to be set in the URL path, you can pass
those parameters in the method arguments:data=api.fetch_tiltmeter(station='selokopo',timestamp__gte='2019-07-01')print(data)Changing the API HostStarting from version 0.9.0, default API host for the library isbma.cendana15.comand usinghttpsprotocol. If you want to change the host,
for example using other hostname or so, you can write the code as follows:frombmaclientimportMonitoringAPIapi=MonitoringAPI(api_key='API_KEY')api.host='SERVER_ADDRESS'Optionally, change HTTP protocol if the server uses different protocol. Choose
eitherhttporhttpsprotocol:api=MonitoringAPI(api_key='API_KEY')api.protocol='https'Note that you should include server port if the server doesn't use standard
port. For example:api.host='SERVER_ADDRESS:PORT'Parameter EncoderAs version 0.10.0, bmaclient addsbmaclient.encoder.ParameterEncoderclass to
enable using native Python object in the query parameters. Default encoder
supports:list, tupleIt will be encoded to bytes string of comma separated values. For example:[1, 2, 3] -> b'1,2,3'
['a', 'b', 'c'] -> b'a,b,c'strstr value will be encoded to bytes string. For example:'param' -> b'param'bytesBytes value will not be touched and returned as it is.int, floatint or float value will be encoded to bytes string. For example:12 -> b'12' 14.56 -> b'14.56'boolBoolean type will be encoded to bytes string with lower case value. For
example:True -> b'true'
False -> b'false'NoneNone value will be encoded to empty bytes string. For example:None -> b''datetime.dateDate object will be encoded to bytes string of date. Default format is%Y-%m-%d. For example:datetime.date(2020, 1, 1) -> b'2020-01-01'datetime.datetimeDatetime object will be encoded to bytes string of datetime. Default format is%Y-%m-%d %H:%M:%M. For example:datetime.datetime(2020, 1, 1, 9, 46, 12) -> b'2020-01-01 09:46:12'otherOther values will be converted to string withstrfunction and encoded with
ASCII encoding unless default function provided.Default encoding is ASCII. If you want to use UTF-8 encoding, subclass
ParameterEncoder and set ensure_ascii to False.Below is an example of subclassing ParameterEncoder class to encode object with
custom type:importdatetimefrombmaclientimportMonitoringAPIfrombmaclient.encoderimportParameterEncoderclassGPSStation(object):"""Custom type."""def__init__(self,code,name):self.code=codeself.name=namedef__str__(self):returnstr(self.code)classCustomParameterEncoder(ParameterEncoder):"""Custom parameter encoder."""defdefault(self,o):"""Override default() method to set custom encoder."""ifisinstance(o,GPSStation):returnstr(o).encode('ascii')returnParameterEncoder.default(self,o)api=MonitoringAPI(api_key='API_KEY',encoder_class=CustomParameterEncoder)pasarbubar=GPSStation('pasarbubar','Pasarbubar')grawah=GPSStation('grawah','Grawah')now=datetime.datetime.now()one_month_ago=now-datetime.timedelta(days=30)data=api.fetch_gps_baseline(station1=pasarbubar,station2=grawah,timestamp__gte=one_month_ago,timestamp__lt=now,nolimit=True,)print(data)Extending API ClassIf you want to extend API class, for example fetching new endpoint that the
method in the library is not available yet, you can see the following example:frombmaclientimportMonitoringAPIfrombmaclient.bindimportbind_methodclassMyMonitoringAPI(MonitoringAPI):def__init__(self,**kwargs):super(MyMonitoringAPI,self).__init__(**kwargs)fetch_gps_baseline=bind_method(path='gps/baseline/',required_parameters=['station1','station2'],doc='Fetch GPS baseline data.')fetch_rsam_seismic=bind_method(path='rsam/seismic/{station}/',accepts_parameters=['station'],doc='Fetch RSAM seismic data.')fetch_cluster_dict=bind_method(path='cluster/dict/',doc='Fetch cluster dictionary.')Request MethodsThe following URL paths are relative to the base API URLhttps://bma.cendana15.com/api/v1/.API NameURL PathPython Method NameCluster Dictionary/cluster/dict/fetch_cluster_dictCluster Seismicity Group/cluster/seisgroup/fetch_cluster_seisgroupDOAS (deprecated since v0.10.0)/doas/fetch_doasDOAS v2/doas2/{station}/fetch_doas2EDM/edm/fetch_edmEDM CSD and Rate/edm/csdr/fetch_csdrEquivalent Energy (since v0.12.0)/equivalent-energy/fetch_equivalent_energyGas Emission/gas/emission/fetch_gas_emissionGas Temperature/gas/temperature/fetch_gas_temperatureGPS Position/gps/position/fetch_gps_positionGPS Baseline/gps/baseline/fetch_gps_baselineLava Domes (since v0.13.0)/lava-domes/fetch_lava_domesMagnetic Imogiri (since v0.15.0)/magnetic/imogiri/fetch_magnetic_imogiriMeteorology/meteorology/fetch_meteorologyPasarbubar Rainfall/meteorology/rainfall/fetch_rainfallPasarbubar Wind Rose/meteorology/windrose/fetch_windroseRockfall-AwanPanas Distance (since v0.13.0)/rfap-distance/fetch_rfap_distanceRockfall-AwanPanas Distance Direction (since v0.14.0)/rfap-distdir/fetch_rfap_distdirRockfall-AwanPanas Rose (since v0.14.0)/rfap-rose/fetch_rfap_roseRockfall-AwanPanas Type (since v0.14.0)/rfap-type/fetch_rfap_typeRSAM Seismic/rsam/seismic/{station}/fetch_rsam_seismicRSAM Seismic Band/rsam/seismic/{station}/{band}/fetch_rsam_seismic_bandRSAM Infrasound/rsam/infrasound/{station}/fetch_rsam_infrasoundRSAM Infrasound Band/rsam/infrasound/{station}/{band}/fetch_rsam_infrasound_bandThermal (deprecated since v0.10.0)/thermal/fetch_thermalThermal v2/thermal2/fetch_thermal2Tiltmeter Platform/tiltmeter/{station}/fetch_tiltmeterTiltmeter Platform Raw/tiltmeter/raw/{station}/fetch_tiltmeter_rawTiltmeter Borehole/tiltborehole/{station}/fetch_tiltboreholeTiltmeter TLR/tiltmeter/tlr/{station}/fetch_tiltmeter_tlrTopography Data/topo/fetch_topoTopography Profile/topo/profile/fetch_topo_profileSeismicity/seismicityfetch_seismicitySeismicity Archive/seismicity/archive/fetch_seismicity_archiveSeismicity Cluster/seismicity/cluster/fetch_seismicity_clusterSeismic Bulletin/bulletin/fetch_bulletinSeismic Energy/energy/fetch_energySeismic Magnitude/magnitude/fetch_magnitudeEDM Slope Correction/slope/fetch_slopeEDM Slope Correction Detail/slope/{pk}/slopeCreate EDM Slope Correction/slope/create_slopeReplace EDM Slope Correction/slope/{pk}/replace_slopeUpdate EDM Slope Correction/slope/{pk}/update_slopeSearch EDM Slope Correction/slope/search_slopeUser Profile Info (deprecated since v0.15.0,will be removed in v0.16.0)/users/fetch_usersUser Detail (deprecated since v0.15.0,will be removed in v0.16.0)/users/{pk}/userSearch User (deprecated since v0.15.0,will be removed in v0.16.0)/users/search_usersFor more information about BMA, seethe BMA
documentation.Bugs ReportingIf you found any bug about this library, you can raise an issue at the followinglink.LicenseCopyright (c) 2019-present BPPTKGBy contributing to the project, you agree that your contributions will be
licensed under its MIT license. SeeLICENSEfor details.