Package: apitable
APITable.pyIt is the official package for the Fusion API of APITable, and provides an API similar to the Django ORM style.Requirementspython3.6 +If you want to call apitable rest api, you need get the API Token first: visit the workbench of APITable, click the avatar in the lower left corner, and go to User Center > Developer Configuration. Click to generate Token (you need to bind your email for the first time).Installationpipinstall--upgradeapitableGetting startedExamplefromapitableimportApitableapitable=Apitable("your api_token")dst=apitable.datasheet("your datasheet id")# When the URL is used as a parameter, the datasheet id is automatically resolved, ignoring the view id.# dst = apitable.datasheet("https://apitable.com/workbench/dstxxxxxxxx/viwxxxxxxxx")# Create a recordrecord=dst.records.create({"title":"new record from Python SDK"})print(record.title)# Create records in bulkrecords=dst.records.bulk_create([{"title":"new record from Python SDK"},{"title":"new record from Python SDK2"}])# Update a single fieldrecord.title="new title"print(record.title)# "new title"# Update multiple fieldsrecord.update({"title":"new title","other_field":"new value",})# Batch update multiple recordsrecords=dst.records.bulk_update([{"recordId":"recxxxxx1","fields":{"title":"new record.title from Python SDK"}},{"recordId":"recxxxxx2","fields":{"title":"new record.title from Python SDK2"}},])# Attachment field updatemy_file=dst.upload_file(<localornetworkfilepath>)record.files=[my_file]# Filter recordsongs=dst_songs.records.filter(artist="faye wong")forsonginsongs:print(song.title)# Batch update a batch of recordsdst_tasks.records.filter(title=None).update(status="Pending")# Get a single recordbook=dst_book.records.get(ISBN="9787506341271")print(book.title)# Convert the record object to jsonrecord.json()# Delete a batch of records that match the filter criteriadst.records.filter(title=None).delete()# Get fieldsforfieldinapitable.datasheet("dstId").fields.all():print(field.name)# Get the fields of the specified view, hidden fields will not be returnedforfieldinapitable.datasheet("dstId").fields.all(viewId="viewId"):print(field.name)# Get viewsforviewinapitable.datasheet("dstId").views.all():print(view.name)Field mappingUsing the field name of the datasheet directly as a variable may not conform to the variable specification. So you have to fall back to using fieldId as the key, making the code less readable.In order to solve this problem, the Python SDK provides the function of field mapping.Bug title!Bug statusThe page crashes after logging inWaitingdst=apitable.datasheet("dstt3KGCKtp11fgK0t",field_key_map={"title":"Bug title!","state":"Bug status",})record=dst.records.get()print(record.title)# "The page crashes after logging in"print(record.state)# "Waiting"record.state="Done"Keep the use of field id as the keybug=apitable.datasheet("dstn2lEFltyGHe2j86",field_key="id")row=bug.records.get(flddpSLHEzDPQ="The page crashes after logging in")row.flddpSLHEzDPQ="The page crashes after logging in"row.update({"flddpSLHEzDPQ":"The page crashes after logging in","fldwvNDf9teD2":"Done"})When specifyingfield_key="id", specify the corresponding key value offield_key_mapshould befieldIdbug=apitable.datasheet("dstn2lEFltyGHe2j86",field_key="id",field_key_map={"title":"flddpSLHEzDPQ","state":"fldwvNDf9teD2",})Documentationrecordsdst.recordsmanage records in datasheets.MethodParameterTypeDescriptionExamplecreatedictRecordCreate a single recorddst.records.create({"title":"new title"})bulk_createdict[]Record[]Create multiple records in batchesdst.records.bulk_create([{"title":"new record1"},{"title":"new record2"}])bulk_updatedict[]Record[]Batch update multiple recordsdst.records.bulk_update([{"recordId": "recxxxxx1", "fields":{"title": "new record.title from Python SDK"}}])all**kwargsQuerySetReturn the record collection, you can pass parameters to customize the return contentdst.records.all()get**kwargsRecordsingle recorddst.records.get(title="new title")get_or_create(defaults,**kwargs)Record,boolQuery the corresponding record through kwargs. If it does not exist, create a new record in combination with defaults. The returned bool indicates whether it is a new record.dst.records.get_or_create(title="new title",defaults={"status":"pending"})update_or_create(defaults,**kwargs)Record,boolQuery the corresponding record through kwargs, and update the record with defaults. Create if it does not exist (same as get_or_create)dst.records.update_or_create(title="new title",defaults={"status":"done"})filter**kwargsQuerySetFilter a batch of recordsdst.records.filter(title="new title")QuerySetChained calls are possible. For example,qs = dst.records.all()returns a batch of queried datasets.MethodParameterTypeDescriptionExamplefilter**dictQuerySetFilter out a batch of recordsqs.filter(title="new title")all/QuerySetReturns a copy of the current record setqs.filter(title="new title").all()get**dictRecordSingle recordqs.get(title="new title")count/intTotal number of recordsqs.filter(title="new title").count()last/RecordLast recordqs.filter(title="new title").last()first/RecordFirst recordqs.filter(title="new title").first()update**dictRecordNumber of records successfully updatedqs.filter(title="new title").update(title="new title")delete/boolWhether the deletion is successfulqs.filter(title="new title").delete()RecordThe QuerySet queried out is a collection of Records. A single Record can obtain the value of the specified field throughrecord.fieldname.Please try to avoid the same name of the field name and the method property reserved by Record, the field with the same name in the table will be obscured. If it does exist, use the field mapping configurationMethod/AttributeParameterTypeDescriptionExamplejson/dictReturns all field values of the current recordrecord.json()_id/str_id is a reserved attribute, returns the recordId of the current recordrecord._idFieldThe mapping relationship between Field and Python data structure. The data with empty cells in the datasheet is always null, and the records returned by the API will not contain fields with null values.Field TypeData typeSingleTextstrTextstrSingleSelectstrMultiSelectstr[]URLstrPhonestrEmailstrNumbernumberCurrencynumberPercentnumberAutoNumbernumberDateTimenumberCreatedTimenumberLastModifiedTimenumberAttachmentattachment object[]Memberunit object[]CheckboxboolRatingintCreatedByunit objectLastModifiedByunit objectMagicLinkstr[]MagicLookUpany[]Formulastr / boolallall method will automatically handle paging loading all resourcesWhen the paging-related parameters (pageNum, pageSize) are passed in, the SDK will no longer automatically load all records, and only return the specified page data。Try to avoid using the dst.records.all method without parameters to get all the data.
The API can obtain a maximum of 1000 pieces of data per request. If your data volume is too large, it is close to the limit of 50000. In the case of no parameters, calling all will serially request the API 50 times. Not only is it very slow, but it consumes API request credit.Return the records of the specified paginationdst.records.all(pageNum=3)Use with viewsSpecifying the view id returns the same data as in the view.dst.records.all(viewId="viwxxxxxx")Filter data using formulasdst.records.all(filterByFormula='{title}="hello"')ParameterTypeDescriptionExampleviewIdstrView ID. The request will return the filtered/sorted results in the viewpageNumintDefault 1pageSizeintDefault 100, maximum 1000sortdict[]Specify the sorting field, which overrides the view sorting conditions[{ field: 'field1', order: 'asc' }]recordIdsstr[]Returns the recordset with the specified recordId['recordId1', 'recordId2']fieldsstr[]Only the specified fields will be returnedfilterByFormulastrReturns matching records using formulas as filter criteriamaxRecordsintLimit the number of records returned, the default is 5000cellFormat'json' or 'string'Defaults to 'json', when specified as 'string' all values will be automatically converted to string format.fieldKey'name' or 'id'Specifies the field query and returned key. The column name 'name' is used by default.See:Tutorial getting started with formulasFAQCan I get the field type (meta) information of the datasheet?Can be get through the fields/views API.Can option be created automatically?If you write to a non-existent option, the option will be created automaticallyHow many records can a single datasheet?5w records.Can more records be processed per request?10 records. In the future, we will adjust the size of this limit according to the actual situation.Can more records be fetched per request?The current maximum is 1000 records. In the future, we will adjust the size of this limit according to the actual situation.Development and testCreate a new.env, the content can refer to.env.example.cp.env.env.exampleThen modify the test code in thetest/folder for testing.pipenvinstall--pre
pipenvshell
python-munittesttest