-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfulcrum-python-2.0-changes.patch
More file actions
997 lines (923 loc) · 42.8 KB
/
Copy pathfulcrum-python-2.0-changes.patch
File metadata and controls
997 lines (923 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
diff --git a/README.md b/README.md
index 566b927..7b191d9 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,52 @@
A library for working with [Fulcrum API](https://learn.fulcrumapp.com/dev/rest/intro/)
+## What's new in 2.0
+
+This release brings the library up to parity with the current Fulcrum API and
+with [fulcrum-js](https://github.com/fulcrumapp/fulcrum-js). Everything from
+1.x still works exactly as before (see "Backwards compatibility" below) - this
+is additive, not a breaking rewrite.
+
+- **New resources**: `groups`, `workflows`, `report_templates`, `batches`,
+ `attachments` (generic upload flow), `users`, `reports` (ad hoc report
+ generation), and `sketches`.
+- **Fuller CRUD on `memberships`**: `find`, `create`, `update`, `delete`, and
+ `for_object(type, object_id)`, in addition to the existing `search` and
+ `change`.
+- **History endpoints**: `forms.history(id)`, `records.history(id)`, and
+ `records.all_history()`.
+- **`records.partial_update(id, obj)`** for `PATCH` support.
+- **Data residency regions**: pass `region=FulcrumRegion.EU` (or `.AU`, `.CA`,
+ `.US`) instead of a raw `uri` string.
+- **Better error handling**: every non-2xx response now raises a typed
+ exception (`fulcrum.exceptions.ForbiddenException`,
+ `UnprocessableEntityException`, etc.) carrying `.status_code` and
+ `.response_body`, instead of silently returning whatever the API sent back
+ for status codes the 1.x client didn't recognize.
+- **`on_request` hook**: `Fulcrum(key='...', on_request=lambda method, path, response: ...)`
+ for wiring up your own logging/tracing (fulcrum-js uses OpenTelemetry for
+ the equivalent purpose; this library stays dependency-free).
+- A `FulcrumClient` alias for the `Fulcrum` class, for anyone porting code or
+ examples over from fulcrum-js.
+- Fixed: `signatures.media()` only supports a `'thumbnail'` size (there is no
+ `'large'` signature variant in the API - the 1.x library's docs and size
+ list were wrong here).
+- Added `videos.thumbnail(id, size='medium', square=False)` for the eight
+ video thumbnail variants the API exposes (`small`/`medium`/`large`/`huge`,
+ each with a square option), which the generic `media()` method can't reach.
+
+## Backwards compatibility
+
+If you're upgrading from 1.x: nothing you're already calling changes. Every
+1.x method, resource, and exception class is still there with the same name
+and the same behavior, including the historically-undocumented
+`memberships.change(...)` helper and `authorizations.regenerate(id)`. New
+functionality is additive. The one intentional behavior change is the error
+handling improvement above - if your code was relying on a 403 or 422 response
+silently *not* raising, it will now raise `ForbiddenException` /
+`UnprocessableEntityException` instead.
+
## Installation
Install via pip:
@@ -20,23 +66,32 @@ Just one - [Requests](http://docs.python-requests.org/en/latest/) takes care of
## Supported Resources and Methods
-| Resource | Methods |
-|---------------------|--------------------------------------|
-| Forms | find, search, create, update, delete |
-| Records | find, search, create, update, delete |
-| Photos | find, search, media, create |
-| Signatures | find, search, media, create |
-| Projects | find, search, create, update, delete |
-| Changesets | find, search, create, update, close |
-| Choice Lists | find, search, create, update, delete |
-| Classification Sets | find, search, create, update, delete |
-| Webhooks | find, search, create, update, delete |
-| Layers | find, search, create, update, delete |
-| Videos | find, search, media, track, create |
-| Audio | find, search, media, track, create |
-| Memberships | search |
-| Roles | search |
-| Audit Logs | search, find |
+| Resource | Methods |
+|---------------------|--------------------------------------------------------------------------|
+| Forms | find, search, create, update, delete, history |
+| Records | find, search, create, update, delete, partial_update, history, all_history |
+| Photos | find, search, media, create |
+| Signatures | find, search, media, create |
+| Sketches | find, search, media, create |
+| Projects | find, search, create, update, delete |
+| Changesets | find, search, create, update, close |
+| Choice Lists | find, search, create, update, delete |
+| Classification Sets | find, search, create, update, delete |
+| Webhooks | find, search, create, update, delete |
+| Layers | find, search, create, update, delete |
+| Videos | find, search, media, thumbnail, track, create |
+| Audio | find, search, media, track, create |
+| Memberships | search, find, create, update, delete, change, change_permissions, for_object |
+| Roles | search |
+| Audit Logs | search, find |
+| Authorizations | find, search, update, delete, regenerate (deprecated) |
+| Groups | find, search, create, update, delete, get_resource, change_permissions |
+| Workflows | find, search, create, update, delete |
+| Report Templates | find, search, create, update, delete |
+| Batches | find, search, create, add_operations, start |
+| Attachments | find, search, create, delete, finalize, copy_all |
+| Users | get |
+| Reports | create, file |
## Usage
@@ -271,8 +326,9 @@ The `size` options are:
| Resource | Sizes |
|---------------------|--------------------------------------|
| Photos | 'original', 'thumbnail', and 'large' |
-| Signatures | 'original', 'thumbnail', and 'large' |
-| Videos | 'original', 'small', and 'medium' |
+| Signatures | 'original' and 'thumbnail' (there is no 'large' variant for signatures) |
+| Sketches | 'original', 'thumbnail', and 'large' |
+| Videos | 'original', 'small', and 'medium' via `media()`; use `videos.thumbnail(id, size, square)` for the thumbnail variants ('small'/'medium'/'large'/'huge', each optionally square) |
| Audio | 'original' |
```python
@@ -377,6 +433,54 @@ print(as_geojson)
# {'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'properties': {'_record_id': 'abc', '_project_id': '123'}, 'geometry': {'type': 'Point', 'coordinates': [-82.63707, 27.77102]}}]}
```
+## New Resources (2.0)
+
+```python
+# Groups
+group = fulcrum.groups.create({'group': {'name': 'Field Crew'}})
+members = fulcrum.groups.get_resource(group['group']['id'], 'members')
+fulcrum.groups.change_permissions({'type': 'group_members', 'group_id': group['group']['id'], 'add': ['user-id']})
+
+# Workflows / Report Templates - standard find/search/create/update/delete
+workflow = fulcrum.workflows.create({'workflow': {'name': 'Auto-assign'}})
+template = fulcrum.report_templates.create({'report_template': {'name': 'Inspection Report', 'form_id': 'f1'}})
+
+# Batches
+batch = fulcrum.batches.create({'batch': {'name': 'Bulk import'}})
+fulcrum.batches.add_operations(batch['batch']['id'], [{'type': 'create', 'resource': {...}}])
+fulcrum.batches.start(batch['batch']['id'])
+
+# Attachments (generic upload flow)
+attachment = fulcrum.attachments.create({'attachment': {'owners': [{'type': 'record', 'record_id': 'r1', 'field_key': 'abc'}]}})
+fulcrum.attachments.finalize({'attachment_id': attachment['attachment']['id']})
+
+# Users
+me = fulcrum.users.get()
+
+# Reports (ad hoc, not tied to a saved report template)
+report = fulcrum.reports.create({'report': {'form_id': 'f1', 'format': 'pdf'}})
+pdf_bytes = fulcrum.reports.file(report['report']['id'])
+
+# Memberships - full CRUD, plus listing permissions for a form/project/layer
+membership = fulcrum.memberships.create({'membership': {'form_id': 'f1', 'user_id': 'u1', 'role': 'editor'}})
+fulcrum.memberships.for_object('form', 'f1')
+
+# History
+fulcrum.records.history('r1')
+fulcrum.records.all_history()
+fulcrum.forms.history('f1')
+
+# Regions
+from fulcrum import Fulcrum, FulcrumRegion
+fulcrum_eu = Fulcrum(key='super-secret-key', region=FulcrumRegion.EU)
+
+# Request hook (logging/tracing)
+def log_request(method, path, response):
+ print(method.upper(), path, response.status_code)
+
+fulcrum = Fulcrum(key='super-secret-key', on_request=log_request)
+```
+
## Examples
https://github.com/fulcrumapp/fulcrum-python/wiki/Examples
@@ -400,15 +504,12 @@ You'll need some additional things to run tests, so:
Run the tests:
- nosetests
-
-You can get coverage too.
-
- nosetests --with-coverage --cover-package fulcrum
+ python -m unittest discover
-View coverage.
+Or, with pytest and coverage:
- nosetests --with-coverage --cover-package fulcrum --cover-html
+ pip install pytest pytest-cov
+ pytest --cov=fulcrum
## Publishing
diff --git a/fulcrum/__init__.py b/fulcrum/__init__.py
index 0092367..0df6d1d 100644
--- a/fulcrum/__init__.py
+++ b/fulcrum/__init__.py
@@ -3,12 +3,14 @@ from fulcrum.api.endpoints import (Forms, Records, Webhooks, Photos,
Memberships, Roles, ChoiceLists, Signatures,
ClassificationSets, Projects, Videos, Audio,
Changesets, ChildRecords, AuditLogs, Layers,
- Authorizations)
+ Authorizations, Groups, Workflows, ReportTemplates,
+ Batches, Attachments, Users, Reports, Sketches)
+from fulcrum.regions import FulcrumRegion
from fulcrum.utils import is_string
-__version__ = '1.12.0'
+__version__ = '2.0.0'
-default_uri = 'https://api.fulcrumapp.com'
+default_uri = FulcrumRegion.US
def create_authorization(email, password, organization_id, note,
@@ -42,14 +44,39 @@ def get_user(email, password):
class Fulcrum(object):
- def __init__(self, key, uri=default_uri):
- self.client = Client(key=key, uri=uri)
+ """Fulcrum API client.
+
+ Backwards compatible with the 1.x library: ``Fulcrum(key='...')`` and
+ ``Fulcrum(key='...', uri='https://api.fulcrumapp.com')`` both still work
+ exactly as before, and every 1.x resource/method is still present.
+
+ New in 2.x:
+
+ - ``region``: pass a :class:`fulcrum.FulcrumRegion` value (or a custom
+ base URL string) instead of ``uri`` for data residency, e.g.
+ ``Fulcrum(key='...', region=FulcrumRegion.EU)``.
+ - ``user_agent``: override the default User-Agent header.
+ - ``on_request``: optional ``callable(method, path, response)`` hook for
+ logging/tracing every API call (fulcrum-js uses OpenTelemetry spans for
+ the equivalent purpose; this library stays dependency-free and lets
+ callers wire up whatever they use instead).
+ - New resources: ``groups``, ``workflows``, ``report_templates``,
+ ``batches``, ``attachments``, ``users``, ``reports``, ``sketches``.
+ - Fuller CRUD on ``memberships`` (previously search + change only).
+ - ``forms``/``records`` gain ``.history()``; ``records`` also gains
+ ``.all_history()`` and ``.partial_update()`` (PATCH).
+ """
+
+ def __init__(self, key, uri=None, region=None, user_agent=None, on_request=None):
+ base = region or uri or default_uri
+ self.client = Client(key=key, uri=base, user_agent=user_agent, on_request=on_request)
self.forms = Forms(client=self.client)
self.records = Records(client=self.client)
self.webhooks = Webhooks(client=self.client)
self.photos = Photos(client=self.client)
self.signatures = Signatures(client=self.client)
+ self.sketches = Sketches(client=self.client)
self.memberships = Memberships(client=self.client)
self.roles = Roles(client=self.client)
self.choice_lists = ChoiceLists(client=self.client)
@@ -63,8 +90,23 @@ class Fulcrum(object):
self.layers = Layers(client=self.client)
self.authorizations = Authorizations(client=self.client)
- def query(self, sql, format = 'json'):
+ # New in 2.x
+ self.groups = Groups(client=self.client)
+ self.workflows = Workflows(client=self.client)
+ self.report_templates = ReportTemplates(client=self.client)
+ self.batches = Batches(client=self.client)
+ self.attachments = Attachments(client=self.client)
+ self.users = Users(client=self.client)
+ self.reports = Reports(client=self.client)
+
+ def query(self, sql, format='json', method='post'):
obj = {'q': sql, 'format': format}
+
+ if method == 'get':
+ params = {'q': sql, 'format': format}
+ return self.client.call('get', 'query', url_params=params,
+ json_content=(format != 'csv'))
+
kwargs = {
'data': obj,
'extra_headers': {'Content-Type': 'application/json'}
@@ -74,3 +116,9 @@ class Fulcrum(object):
api_resp = self.client.call('post', 'query', **kwargs)
return api_resp
+
+
+# Alias matching fulcrum-js's class name, for discoverability when porting
+# code/examples over from JS. Fulcrum is the primary, backwards-compatible
+# name and both refer to the exact same class.
+FulcrumClient = Fulcrum
diff --git a/fulcrum/api/__init__.py b/fulcrum/api/__init__.py
index a6b326e..4702ea3 100644
--- a/fulcrum/api/__init__.py
+++ b/fulcrum/api/__init__.py
@@ -3,7 +3,8 @@ import json
import requests
import fulcrum
-from fulcrum.exceptions import (NotFoundException, UnauthorizedException,
+from fulcrum.exceptions import (FulcrumAPIException, NotFoundException, UnauthorizedException,
+ ForbiddenException, UnprocessableEntityException,
InternalServerErrorException,
RateLimitExceededException, BadRequestException)
@@ -12,20 +13,28 @@ class Client(object):
http_exception_map = {
400: BadRequestException,
401: UnauthorizedException,
+ 403: ForbiddenException,
404: NotFoundException,
+ 422: UnprocessableEntityException,
429: RateLimitExceededException,
500: InternalServerErrorException,
}
- def __init__(self, key, uri):
+ def __init__(self, key, uri, user_agent=None, on_request=None):
self.key = key
self.api_root = '{0}/api/v2/'.format(uri)
+ self.user_agent = user_agent
+ # Optional hook: callable(method, path, response) -> None.
+ # Lets callers wire up their own logging/tracing without this
+ # library taking a hard dependency on any particular APM library
+ # (fulcrum-js uses OpenTelemetry spans for this same purpose).
+ self.on_request = on_request
def call(self, method, path, data=None, extra_headers=None, url_params=None, json_content=True, files=None, auth=None):
full_path = self.api_root + path
headers = {
- 'User-Agent': 'Fulcrum Python API Client, Version {}'.format(fulcrum.__version__),
+ 'User-Agent': self.user_agent or 'Fulcrum Python API Client, Version {}'.format(fulcrum.__version__),
}
if self.key:
@@ -56,8 +65,16 @@ class Client(object):
resp = getattr(requests, method)(full_path, **kwargs)
- if resp.status_code in self.http_exception_map:
- raise self.http_exception_map[resp.status_code]
+ if self.on_request is not None:
+ self.on_request(method, path, resp)
+
+ if resp.status_code >= 400:
+ exc_class = self.http_exception_map.get(resp.status_code, FulcrumAPIException)
+ try:
+ body = resp.json()
+ except ValueError:
+ body = resp.text
+ raise exc_class(status_code=resp.status_code, response_body=body)
if method == 'delete' or (method == 'put' and 'close' in path):
# No body is returned for delete and close methods.
diff --git a/fulcrum/api/endpoints.py b/fulcrum/api/endpoints.py
index 4751586..98f8756 100644
--- a/fulcrum/api/endpoints.py
+++ b/fulcrum/api/endpoints.py
@@ -1,20 +1,18 @@
-from fulcrum.mixins import Findable, Deleteable, Createable, Searchable, Updateable, Media, Track, MediaCreateable
+from fulcrum.mixins import (Findable, Deleteable, Createable, Searchable, Updateable,
+ PartialUpdateable, Historyable, AllHistoryable, Closeable,
+ Media, Track, MediaCreateable, ChangePermissionsable,
+ SubResourceGettable, Startable, OperationsAddable, Finalizable)
from . import BaseAPI
-class Forms(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable):
+class Forms(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable, Historyable):
path = 'forms'
-
- def history(self, id, url_params=None):
- api_resp = api_resp = self.client.call('get', '{0}/{1}/history'.format(self.path, id), url_params=url_params)
- return api_resp
-class Records(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable):
+
+class Records(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable,
+ PartialUpdateable, Historyable, AllHistoryable):
path = 'records'
- def history(self, id):
- api_resp = api_resp = self.client.call('get', '{0}/{1}/history'.format(self.path, id))
- return api_resp
class Webhooks(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable):
path = 'webhooks'
@@ -32,12 +30,27 @@ class Photos(BaseAPI, Findable, Searchable, Media, MediaCreateable):
class Signatures(BaseAPI, Findable, Searchable, Media, MediaCreateable):
path = 'signatures'
ext = 'png'
- sizes = ['thumbnail', 'large']
+ # Note: unlike photos, the API only exposes a thumbnail size for
+ # signatures (no "large" variant) - see /v2/signatures/{id}/thumbnail.png
+ # in the OpenAPI spec.
+ sizes = ['thumbnail']
media_upload_path = ''
media_form_field_name = 'signature'
default_content_type = 'image/png'
+class Sketches(BaseAPI, Findable, Searchable, Media, MediaCreateable):
+ """Sketches - present in the current Fulcrum API spec but not exposed by
+ either the legacy Python library or the current fulcrum-js wrapper.
+ Included here for full API coverage."""
+ path = 'sketches'
+ ext = 'jpg'
+ sizes = ['thumbnail', 'large']
+ media_upload_path = ''
+ media_form_field_name = 'sketch'
+ default_content_type = 'image/jpeg'
+
+
class Videos(BaseAPI, Findable, Searchable, Media, Track, MediaCreateable):
path = 'videos'
ext = 'mp4'
@@ -46,6 +59,16 @@ class Videos(BaseAPI, Findable, Searchable, Media, Track, MediaCreateable):
media_form_field_name = 'video'
default_content_type = 'video/mp4'
+ thumbnail_sizes = ['small', 'medium', 'large', 'huge']
+
+ def thumbnail(self, id, size='medium', square=False):
+ """Get a video thumbnail. size is one of 'small', 'medium', 'large', 'huge'."""
+ if size not in self.thumbnail_sizes:
+ raise ValueError('Size {} not supported'.format(size))
+ suffix = '_square' if square else ''
+ path = '{0}/{1}/thumbnail_{2}{3}.jpg'.format(self.path, id, size, suffix)
+ return self.client.call('get', path, json_content=False)
+
class Audio(BaseAPI, Findable, Searchable, Media, Track, MediaCreateable):
path = 'audio'
@@ -56,10 +79,15 @@ class Audio(BaseAPI, Findable, Searchable, Media, Track, MediaCreateable):
default_content_type = 'audio/mp3'
-class Memberships(BaseAPI, Searchable):
+class Memberships(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable):
path = 'memberships'
def change(self, resource_type, id, action, membership_ids):
+ """Legacy helper - kept for backwards compatibility.
+
+ Prefer change_permissions() for new code, which mirrors the API
+ payload shape more directly.
+ """
change = {
'type': '{}_members'.format(resource_type),
'{}_id'.format(resource_type): id,
@@ -71,6 +99,24 @@ class Memberships(BaseAPI, Searchable):
extra_headers={'Content-Type': 'application/json'})
return api_resp
+ def change_permissions(self, change):
+ data = {'change': change}
+ api_resp = self.client.call('post', 'memberships/change_permissions',
+ data=data,
+ extra_headers={'Content-Type': 'application/json'})
+ return api_resp
+
+ def for_object(self, resource_type, object_id, url_params=None):
+ """GET /permissions.json?type=<resource_type>&object_id=<object_id>
+
+ Returns all memberships/permissions for a given form, project, or layer.
+ """
+ params = dict(url_params or {})
+ params['type'] = resource_type
+ params['object_id'] = object_id
+ api_resp = self.client.call('get', 'permissions', url_params=params)
+ return api_resp
+
class Roles(BaseAPI, Searchable):
path = 'roles'
@@ -88,15 +134,14 @@ class Projects(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable
path = 'projects'
-class Changesets(BaseAPI, Findable, Createable, Searchable, Updateable):
+class Changesets(BaseAPI, Findable, Createable, Searchable, Updateable, Closeable):
path = 'changesets'
- def close(self, id):
- api_resp = api_resp = self.client.call('put', '{0}/{1}/close'.format(self.path, id))
- return api_resp
-
class ChildRecords(BaseAPI, Searchable):
+ """Deprecated - not present in the current Fulcrum API OpenAPI spec.
+ Kept only so existing integrations that call this don't break at import
+ time; the endpoint itself may no longer exist server-side."""
path = 'child_records'
@@ -112,5 +157,54 @@ class Authorizations(BaseAPI, Findable, Deleteable, Searchable, Updateable):
path = 'authorizations'
def regenerate(self, id):
+ """Deprecated - not present in the current Fulcrum API OpenAPI spec.
+ Kept only for backwards compatibility with existing integrations."""
api_resp = self.client.call('post', '{}/{}/regenerate'.format(self.path, id))
return api_resp
+
+
+class Groups(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable,
+ SubResourceGettable, ChangePermissionsable):
+ path = 'groups'
+ change_permissions_path = 'groups/change_permissions'
+
+
+class Workflows(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable):
+ path = 'workflows'
+
+
+class ReportTemplates(BaseAPI, Findable, Deleteable, Createable, Searchable, Updateable):
+ path = 'report_templates'
+
+
+class Batches(BaseAPI, Findable, Createable, Searchable, OperationsAddable, Startable):
+ path = 'batch'
+
+
+class Attachments(BaseAPI, Findable, Deleteable, Createable, Searchable, Finalizable):
+ path = 'attachments'
+
+ def copy_all(self, obj):
+ api_resp = self.client.call('post', '{0}/copy_all'.format(self.path), data=obj,
+ extra_headers={'Content-Type': 'application/json'})
+ return api_resp
+
+
+class Users(BaseAPI):
+ path = 'users'
+
+ def get(self, url_params=None):
+ api_resp = self.client.call('get', self.path, url_params=url_params)
+ return api_resp
+
+
+class Reports(BaseAPI, Createable):
+ """Ad hoc report generation - present in the API spec but not wrapped by
+ either the legacy Python library or the current fulcrum-js wrapper
+ (both leave it to be called through their generic/low-level client).
+ Included here for full API coverage."""
+ path = 'reports'
+
+ def file(self, report_id):
+ api_resp = self.client.call('get', '{0}/{1}.pdf'.format(self.path, report_id), json_content=False)
+ return api_resp
diff --git a/fulcrum/exceptions.py b/fulcrum/exceptions.py
index 13804db..8e4eb0c 100644
--- a/fulcrum/exceptions.py
+++ b/fulcrum/exceptions.py
@@ -2,20 +2,45 @@ class InvalidAPIVersionException(Exception):
"""An invalid API version was passed."""
-class NotFoundException(Exception):
- """The resource could not be found."""
+class FulcrumAPIException(Exception):
+ """Base class for exceptions raised for a non-2xx response from the API.
+ Carries the HTTP status code and the parsed (or raw) response body so
+ callers that need more than an exception type/message can still get at
+ the details the API returned.
+ """
-class UnauthorizedException(Exception):
- """The API key supplied is not authorized to access this resource."""
+ def __init__(self, status_code=None, response_body=None, message=None):
+ self.status_code = status_code
+ self.response_body = response_body
+ super(FulcrumAPIException, self).__init__(
+ message or 'Fulcrum API request failed with status {0}'.format(status_code)
+ )
-class InternalServerErrorException(Exception):
- """There was an error while processing your request."""
+class BadRequestException(FulcrumAPIException):
+ """There was a problem with your request. (HTTP 400)"""
-class RateLimitExceededException(Exception):
- """The API key's rate limit was exceeded."""
+class UnauthorizedException(FulcrumAPIException):
+ """The API key supplied is not authorized to access this resource. (HTTP 401)"""
-class BadRequestException(Exception):
- """There was a problem with your request."""
+
+class ForbiddenException(FulcrumAPIException):
+ """The API key is valid but not permitted to perform this action. (HTTP 403)"""
+
+
+class NotFoundException(FulcrumAPIException):
+ """The resource could not be found. (HTTP 404)"""
+
+
+class UnprocessableEntityException(FulcrumAPIException):
+ """The request was well-formed but failed validation. (HTTP 422)"""
+
+
+class RateLimitExceededException(FulcrumAPIException):
+ """The API key's rate limit was exceeded. (HTTP 429)"""
+
+
+class InternalServerErrorException(FulcrumAPIException):
+ """There was an error while processing your request. (HTTP 5xx)"""
diff --git a/fulcrum/mixins.py b/fulcrum/mixins.py
index 2ace104..86e73a3 100644
--- a/fulcrum/mixins.py
+++ b/fulcrum/mixins.py
@@ -1,5 +1,6 @@
from fulcrum.utils import is_string, generate_uuid
+
class Findable(object):
def find(self, id):
api_resp = self.client.call('get', '{0}/{1}'.format(self.path, id))
@@ -29,6 +30,36 @@ class Updateable(object):
return api_resp
+class PartialUpdateable(object):
+ """PATCH support - currently only records.json supports this in the API."""
+
+ def partial_update(self, id, obj):
+ api_resp = self.client.call('patch', '{0}/{1}'.format(self.path, id), data=obj, extra_headers={'Content-Type': 'application/json'})
+ return api_resp
+
+
+class Historyable(object):
+ """Adds history(id) for resources exposing a /{id}/history endpoint (records, forms)."""
+
+ def history(self, id, url_params=None):
+ api_resp = self.client.call('get', '{0}/{1}/history'.format(self.path, id), url_params=url_params)
+ return api_resp
+
+
+class AllHistoryable(object):
+ """Adds all_history() for resources exposing a /history endpoint across all records."""
+
+ def all_history(self, url_params=None):
+ api_resp = self.client.call('get', '{0}/history'.format(self.path), url_params=url_params)
+ return api_resp
+
+
+class Closeable(object):
+ def close(self, id):
+ api_resp = self.client.call('put', '{0}/{1}/close'.format(self.path, id))
+ return api_resp
+
+
class Media(object):
def media(self, id, size='original'):
if size == 'original':
@@ -79,3 +110,53 @@ class MediaCreateable(object):
api_resp = self.client.call('post', self.path + self.media_upload_path, data=data, files=files)
return api_resp
+
+
+class ChangePermissionsable(object):
+ """Adds change_permissions() for resources with a /change_permissions action
+ (memberships and groups both expose this pattern)."""
+
+ change_permissions_path = None # defaults to '{path}/change_permissions'
+
+ def change_permissions(self, change):
+ path = self.change_permissions_path or '{0}/change_permissions'.format(self.path)
+ api_resp = self.client.call('post', path, data={'change': change},
+ extra_headers={'Content-Type': 'application/json'})
+ return api_resp
+
+
+class SubResourceGettable(object):
+ """Adds get_resource(id, resource) for resources exposing GET /{id}/{resource}
+ (used by groups to list a group's members/forms/etc.)."""
+
+ def get_resource(self, id, resource, url_params=None):
+ api_resp = self.client.call('get', '{0}/{1}/{2}'.format(self.path, id, resource), url_params=url_params)
+ return api_resp
+
+
+class Startable(object):
+ """Adds start(id) for resources with a /start action (batches)."""
+
+ def start(self, id, obj=None):
+ api_resp = self.client.call('post', '{0}/{1}/start'.format(self.path, id), data=obj,
+ extra_headers={'Content-Type': 'application/json'} if obj is not None else None)
+ return api_resp
+
+
+class OperationsAddable(object):
+ """Adds add_operations(id, operations) for batches."""
+
+ def add_operations(self, id, operations):
+ api_resp = self.client.call('post', '{0}/{1}/operations'.format(self.path, id),
+ data={'operations': operations},
+ extra_headers={'Content-Type': 'application/json'})
+ return api_resp
+
+
+class Finalizable(object):
+ """Adds finalize(obj) for the generic attachments upload flow."""
+
+ def finalize(self, obj):
+ api_resp = self.client.call('post', '{0}/finalize'.format(self.path), data=obj,
+ extra_headers={'Content-Type': 'application/json'})
+ return api_resp
diff --git a/fulcrum/regions.py b/fulcrum/regions.py
new file mode 100644
index 0000000..69af745
--- /dev/null
+++ b/fulcrum/regions.py
@@ -0,0 +1,15 @@
+class FulcrumRegion(object):
+ """Data residency regions for the Fulcrum API.
+
+ Mirrors the ``FulcrumRegion`` enum in fulcrum-js. Pass one of these as
+ the ``region`` argument to :class:`fulcrum.Fulcrum`, or pass a custom
+ base URL string for a region not listed here.
+
+ Note these are *host* values (no ``/api`` suffix) - the client appends
+ ``/api/v2/`` itself, matching this library's existing ``uri`` convention.
+ """
+
+ US = 'https://api.fulcrumapp.com'
+ AU = 'https://api.fulcrumapp-au.com'
+ CA = 'https://api.fulcrumapp-ca.com'
+ EU = 'https://api.fulcrumapp-eu.com'
diff --git a/setup.py b/setup.py
index 72943ae..d1c0314 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ requires = ['requests>=2.11.0']
setup(
name='fulcrum',
- version='1.12.0',
+ version='2.0.0',
description='A python wrapper for the Fulcrum API',
author='Jason Sanford',
author_email='jasonsanford@gmail.com',
diff --git a/test_requirements.txt b/test_requirements.txt
index ac7ce68..2e46442 100644
--- a/test_requirements.txt
+++ b/test_requirements.txt
@@ -1,4 +1,3 @@
-httpretty==0.9.7
-coverage==5.0.3
-nose==1.3.7
-requests==2.22.0
+httpretty>=1.1.4
+coverage>=7.0
+requests>=2.28.0
diff --git a/tests/test_new_resources.py b/tests/test_new_resources.py
new file mode 100644
index 0000000..0e2d715
--- /dev/null
+++ b/tests/test_new_resources.py
@@ -0,0 +1,199 @@
+import httpretty
+
+from fulcrum import Fulcrum, FulcrumRegion
+from fulcrum.exceptions import ForbiddenException, UnprocessableEntityException
+
+from tests import FulcrumTestCase
+
+
+class GroupTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_crud_and_actions(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/groups',
+ body='{"groups": [{"id": "g1"}], "total_count": 1}', status=200)
+ self.assertEqual(self.fulcrum_api.groups.search()['total_count'], 1)
+
+ httpretty.register_uri(httpretty.GET, self.api_root + '/groups/g1',
+ body='{"group": {"id": "g1", "name": "Field Crew"}}', status=200)
+ self.assertEqual(self.fulcrum_api.groups.find('g1')['group']['name'], 'Field Crew')
+
+ httpretty.register_uri(httpretty.POST, self.api_root + '/groups',
+ body='{"group": {"id": "g2"}}', status=200)
+ self.assertEqual(self.fulcrum_api.groups.create({'group': {'name': 'New'}})['group']['id'], 'g2')
+
+ httpretty.register_uri(httpretty.PUT, self.api_root + '/groups/g1',
+ body='{"group": {"id": "g1", "name": "Renamed"}}', status=200)
+ self.assertEqual(self.fulcrum_api.groups.update('g1', {'group': {'name': 'Renamed'}})['group']['name'], 'Renamed')
+
+ httpretty.register_uri(httpretty.GET, self.api_root + '/groups/g1/forms',
+ body='{"forms": []}', status=200)
+ self.assertEqual(self.fulcrum_api.groups.get_resource('g1', 'forms'), {'forms': []})
+
+ httpretty.register_uri(httpretty.POST, self.api_root + '/groups/change_permissions',
+ body='{"success": true}', status=200)
+ self.assertTrue(self.fulcrum_api.groups.change_permissions({'type': 'form_members'})['success'])
+
+ httpretty.register_uri(httpretty.DELETE, self.api_root + '/groups/g1', status=200)
+ self.fulcrum_api.groups.delete('g1')
+
+
+class WorkflowTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_crud(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/workflows',
+ body='{"workflows": []}', status=200)
+ self.assertEqual(self.fulcrum_api.workflows.search(), {'workflows': []})
+
+ httpretty.register_uri(httpretty.POST, self.api_root + '/workflows',
+ body='{"workflow": {"id": "w1"}}', status=200)
+ self.assertEqual(self.fulcrum_api.workflows.create({'workflow': {}})['workflow']['id'], 'w1')
+
+
+class ReportTemplateTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_crud(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/report_templates',
+ body='{"report_templates": []}', status=200)
+ self.assertEqual(self.fulcrum_api.report_templates.search(), {'report_templates': []})
+
+ httpretty.register_uri(httpretty.DELETE, self.api_root + '/report_templates/rt1', status=200)
+ self.fulcrum_api.report_templates.delete('rt1')
+
+
+class BatchTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_create_add_operations_start(self):
+ httpretty.register_uri(httpretty.POST, self.api_root + '/batch',
+ body='{"batch": {"id": "b1"}}', status=200)
+ batch = self.fulcrum_api.batches.create({'batch': {}})
+ self.assertEqual(batch['batch']['id'], 'b1')
+
+ httpretty.register_uri(httpretty.POST, self.api_root + '/batch/b1/operations',
+ body='{"success": true}', status=200)
+ self.assertTrue(self.fulcrum_api.batches.add_operations('b1', [{'type': 'create'}])['success'])
+
+ httpretty.register_uri(httpretty.POST, self.api_root + '/batch/b1/start',
+ body='{"success": true}', status=200)
+ self.assertTrue(self.fulcrum_api.batches.start('b1')['success'])
+
+
+class AttachmentTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_create_finalize_delete(self):
+ httpretty.register_uri(httpretty.POST, self.api_root + '/attachments',
+ body='{"attachment": {"id": "a1"}, "headers": {}}', status=200)
+ self.assertEqual(self.fulcrum_api.attachments.create({})['attachment']['id'], 'a1')
+
+ httpretty.register_uri(httpretty.POST, self.api_root + '/attachments/finalize',
+ body='{"attachment": {"id": "a1", "status": "stored"}}', status=200)
+ self.assertEqual(self.fulcrum_api.attachments.finalize({'attachment_id': 'a1'})['attachment']['status'], 'stored')
+
+ httpretty.register_uri(httpretty.DELETE, self.api_root + '/attachments/a1', status=200)
+ self.fulcrum_api.attachments.delete('a1')
+
+
+class UsersTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_get(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/users',
+ body='{"user": {"id": "u1"}}', status=200)
+ self.assertEqual(self.fulcrum_api.users.get()['user']['id'], 'u1')
+
+
+class ReportsTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_create_and_file(self):
+ httpretty.register_uri(httpretty.POST, self.api_root + '/reports',
+ body='{"report": {"id": "r1"}}', status=200)
+ self.assertEqual(self.fulcrum_api.reports.create({'report': {}})['report']['id'], 'r1')
+
+ httpretty.register_uri(httpretty.GET, self.api_root + '/reports/r1.pdf',
+ body=b'%PDF-1.4 fake pdf bytes', status=200)
+ self.assertEqual(self.fulcrum_api.reports.file('r1'), b'%PDF-1.4 fake pdf bytes')
+
+
+class MembershipFullCrudTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_create_find_update_delete(self):
+ httpretty.register_uri(httpretty.POST, self.api_root + '/memberships',
+ body='{"membership": {"id": "m1"}}', status=200)
+ self.assertEqual(self.fulcrum_api.memberships.create({'membership': {}})['membership']['id'], 'm1')
+
+ httpretty.register_uri(httpretty.GET, self.api_root + '/memberships/m1',
+ body='{"membership": {"id": "m1"}}', status=200)
+ self.assertEqual(self.fulcrum_api.memberships.find('m1')['membership']['id'], 'm1')
+
+ httpretty.register_uri(httpretty.PUT, self.api_root + '/memberships/m1',
+ body='{"membership": {"id": "m1", "role": "admin"}}', status=200)
+ self.assertEqual(self.fulcrum_api.memberships.update('m1', {'membership': {}})['membership']['role'], 'admin')
+
+ httpretty.register_uri(httpretty.DELETE, self.api_root + '/memberships/m1', status=200)
+ self.fulcrum_api.memberships.delete('m1')
+
+ @httpretty.activate
+ def test_for_object(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/permissions',
+ body='{"memberships": []}', status=200)
+ self.assertEqual(self.fulcrum_api.memberships.for_object('form', 'f1'), {'memberships': []})
+
+ @httpretty.activate
+ def test_legacy_change_still_works(self):
+ httpretty.register_uri(httpretty.POST, self.api_root + '/memberships/change_permissions',
+ body='{"success": true}', status=200)
+ self.assertTrue(self.fulcrum_api.memberships.change('form', 'f1', 'add', ['m1'])['success'])
+
+
+class HistoryTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_records_all_history(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/records/history',
+ body='{"history": []}', status=200)
+ self.assertEqual(self.fulcrum_api.records.all_history(), {'history': []})
+
+ @httpretty.activate
+ def test_records_partial_update(self):
+ httpretty.register_uri(httpretty.PATCH, self.api_root + '/records/r1',
+ body='{"record": {"id": "r1"}}', status=200)
+ self.assertEqual(self.fulcrum_api.records.partial_update('r1', {'record': {}})['record']['id'], 'r1')
+
+
+class RegionTest(FulcrumTestCase):
+ def test_region_changes_api_root(self):
+ api = Fulcrum(key='k', region=FulcrumRegion.EU)
+ self.assertEqual(api.client.api_root, 'https://api.fulcrumapp-eu.com/api/v2/')
+
+ def test_uri_still_works_for_backwards_compat(self):
+ api = Fulcrum(key='k', uri='https://api.fulcrumapp-au.com')
+ self.assertEqual(api.client.api_root, 'https://api.fulcrumapp-au.com/api/v2/')
+
+ def test_defaults_to_us(self):
+ api = Fulcrum(key='k')
+ self.assertEqual(api.client.api_root, FulcrumRegion.US + '/api/v2/')
+
+
+class ErrorMappingTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_403_maps_to_forbidden(self):
+ httpretty.register_uri(httpretty.GET, self.api_root + '/forms/x', status=403,
+ body='{"message": "forbidden"}')
+ with self.assertRaises(ForbiddenException) as ctx:
+ self.fulcrum_api.forms.find('x')
+ self.assertEqual(ctx.exception.status_code, 403)
+
+ @httpretty.activate
+ def test_422_maps_to_unprocessable_entity(self):
+ httpretty.register_uri(httpretty.POST, self.api_root + '/forms', status=422,
+ body='{"form_errors": {"name": ["can\'t be blank"]}}')
+ with self.assertRaises(UnprocessableEntityException) as ctx:
+ self.fulcrum_api.forms.create({'form': {}})
+ self.assertIn('name', ctx.exception.response_body['form_errors'])
+
+
+class OnRequestHookTest(FulcrumTestCase):
+ @httpretty.activate
+ def test_hook_is_called(self):
+ seen = []
+ api = Fulcrum(key='k', on_request=lambda method, path, resp: seen.append((method, path, resp.status_code)))
+ httpretty.register_uri(httpretty.GET, self.api_root + '/forms', body='{"forms": []}', status=200)
+ api.forms.search()
+ self.assertEqual(seen, [('get', 'forms', 200)])
diff --git a/tests/test_photo.py b/tests/test_photo.py
index 1752a9b..97eaf03 100644
--- a/tests/test_photo.py
+++ b/tests/test_photo.py
@@ -1,5 +1,4 @@
import httpretty
-from nose.tools import raises
from tests import FulcrumTestCase
@@ -15,14 +14,14 @@ class PhotoTest(FulcrumTestCase):
self.assertIsInstance(photo, dict)
self.assertEqual(photo['photo']['id'], 'abc-123')
- @raises(AttributeError)
def test_missing_delete(self):
- self.fulcrum_api.photos.delete('abc-123')
+ with self.assertRaises(AttributeError):
+ self.fulcrum_api.photos.delete('abc-123')
- @raises(AttributeError)
def test_missing_create(self):
- self.fulcrum_api.photos.create({'id': 'abc-123'})
+ with self.assertRaises(AttributeError):
+ self.fulcrum_api.photos.create({'id': 'abc-123'})
- @raises(AttributeError)
def test_missing_update(self):
- self.fulcrum_api.photos.update('abc-123', {'id': 'abc-123'})
+ with self.assertRaises(AttributeError):
+ self.fulcrum_api.photos.update('abc-123', {'id': 'abc-123'})