NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI
PyPI, #1207 most downloaded on PyPI
Microsoft 365 & Microsoft Graph Library for Python
Latest stable
3.3.1
Last release 15 days ago
07 Nov 2026
Ships unpredictably
gaps range from 2 weeks to 1.2 years
Nearly every release is documented
notes for 56 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
10 years old
63 releases · first in 2017
Drag across the ruler to compare, or tap a release to open it.
Two stories: model types now declare the OData metadata they read — every getter names the member behind it, and a type's schema derives its projectio
Two stories: model types now declare the OData metadata they read — every getter names the member behind it, and a type's schema derives its projections from those declarations instead of a hand-kept list — and the migration layer became a set of portable trees, so an export of mail, calendars, contacts or a whole bundle can be inspected, resumed and imported into another tenant.
office365.sharepoint, 6,911 across 1,057 Graph modules — and TypeSchema derives its projections from that index. TypeSchema.of(Web).columns goes 39 → 118 names (.navigations 2 → 50), List 21 → 98, User 21 → 81, Group 13 → 53. Request bodies are unchanged: a declaration says what a response carries, never what a request must send.@key(...), @version(...), @odata(navigation=True), @odata(system=True), @odata(compare=Compare(format="date")) and a facet= by role (columns_of_facet("permissions")), read from _schema rather than re-scanned.ClientValue.__init_subclass__ applies dataclass(cls, repr=False) once and reads the schema from those fields, with @dataclass_transform() telling a type checker what the decorator used to.readonly from a live write-and-read-back probe — all 37 of File, 43 more on ListItem, 13 on Folder — and List (41 of its 98 columns) and Web (62) answer the same question, so to_json(profile) no longer echoes a server-owned value. hydrate(payload) is the read verb on ClientObject and ClientValue, and JsonProfile.scoped(Model, only=..., without=...) narrows any profile to one model.MailFolderSource/MailExportTarget with EmlTreeSource/MailboxTarget, CalendarSource/IcsExportTarget with IcsTreeSource/CalendarTarget, ContactSource/VcfExportTarget with VcfTreeSource/ContactTarget. A sidecar is the model's own JSON plus provenance, mail is verified by mime_digest (Exchange re-serialises every message it stores), and a resumed run skips what is already on disk.BundleTarget/BundleSource in office365.migration.adapters write content/<sha256[:2]>/<sha256>, an append-only manifest.ndjson and a bundle.json derived from it — content-addressed, idempotent, byte-identical on a re-seal — and the same bundle reads back as a source for another target. A fidelity the bundle cannot carry is refused at plan(), not lost at run().office365.permissions exports require_permission, declared, Requirement, ResourceName and index; a declaration names the API resource its names belong to; 413 tenant-administration operations, 54 migration operations and the SharePoint everyday objects declare a rung (READ → WRITE → MANAGE → FULL_CONTROL). TokenClaims reads a JWT's audience, scp and roles without verifying it, and catalog(resource) answers what an API actually publishes.quotas module per product, registered at import, @limit composing over a class and limits_of(cls); Operation.stream()/wait() with Retry-After pacing, jitter, progress and cancel, and a partiallySucceeded outcome that is terminal-but-neither.to_json() 62% less time (#1069), parse_datetime 15.6× (#1067), ODataPathBuilder 17.8% (#1068), Progress snapshots 7.7% (#1066).$select drops silently. Any code that read select_all() and friends by hand now reads TypeSchema.of(T).columns; expand_all() is .expansions, select_facet(f) is .columns_of_facet(f), odata_name(a) is .name_of(a) — on a ClientValue too.ClientValue subclass no longer takes @dataclass: the base applies it once in __init_subclass__, and a second pass over fields the first consumed makes a different class. Drop the decorator.team.json is team.to_json(), a mailbox sidecar is Message.to_json() plus three provenance keys. TeamRecord, ChannelRecord, MemberRecord, TabRecord, AppRecord, PagePayload and NavNode/WebNavigation are gone, IcsProfile is IcsDialect, and a tree written by a pre-release build is refused by name instead of importing as empty fields.office365.permissions; office365.directory.permissions is gone. declared(method, flow=...) raises rather than answering an empty requirement when the method names nothing under that flow.SP.User loses the 58 profile getters that duplicated SP.Directory.User, plus Web.site_id and office365.sharepoint.workflow.task; MigrationItem no longer carries author_id/editor_id (they are item.author.user_id), and the old keywords raise TypeError.SPModerationStatusType member, not the raw integer, so a comparison against a literal reads false; SitePage.moderation_status is readonly as well.filelock and tornado declares requires-python >=3.11.order_by never reached the service: QueryOptions emitted its Python attribute names, so a sorted read asked for $order_by, which Graph answers 200 to and ignores. Standard options are spelled as the specification spells them (#1063).$select read narrowed every later read of the object it was made on: ReadEntityQuery appended its properties to the object's own query_options.SitePageFieldsData(Title="x") serialises as {"Title": "x"}, not {"Title": "x", "CoAuthState": {}}, so a farm that never had that property does not refuse the create (#1060).List.export() exported files: the loop compared the wire's number against FileSystemObjectType.File and 0 == File is False. A multi-value column can be updated ({"results": [...]}, the only shape either write accepts), a team site is no longer returned before it exists, and a page's web parts ask for the cast that names the type.execute_query_retry retried on its own backoff and ignored Retry-After. to_json() no longer emits __-prefixed bookkeeping (__etag, __odata_type), and DateTimeTimeZone.parse() reads a Graph dict, so EventCollection.add(start={...}) works.SignIn.location reads the location rather than the status.serverRelativeUrl → server_relative_url rename is documented as breaking, with the migration shown (#1037).📄 Full changelog: CHANGELOG.md · 📦 pip install --upgrade office365-rest-python-client
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Two changes shape this line. Model types now declare what they read: every getter names the OData member behind it, and a type's schema derives its projections from those declarations instead of a hand-kept list. The migration layer becomes a set of portable trees — mail, calendars, contacts and a bundle — so an export can be inspected, resumed and imported into another tenant.
team.json is team.to_json() with
members, installedApps and channels attached, and messages.ndjson lines are
message.to_json() plus channel_id. TeamRecord, ChannelRecord, MemberRecord,
TabRecord and AppRecord are removed, with the extractor behind them;
TeamsExportOptions moved to migration.teams.adapters.Message.to_json(), Event.to_json(),
Contact.to_json() — plus three provenance keys a model cannot know. A tree written by
a pre-release build is refused by name (refuse_legacy_sidecar) instead of importing as
empty fields.TypeSchema.of(Web).columns goes 39 → 118 names and .navigations
2 → 50, List 21 → 98, File 11 → 37, Field 3 → 41. A projection built from the old
lists asked for navigation properties, which $select drops silently. Request bodies
are unchanged: a declaration says what a response may carry, never what a request must.User goes 21 → 81
columns, Group 13 → 53, DriveItem 10 → 32, Team 9 → 17, Channel 5 → 13. 175
members that were declared as columns are now declared as navigations, so $select no
longer asks for them. Request bodies are unchanged.readonly from a live write-and-read-back probe — all 37 of File, 43 more on
ListItem, 13 on Folder, 17 on Field, 6 on ContentType. to_json(profile) drops
them, so a request no longer echoes a server-owned value back.@odata(..., selectable=False) replaces ClientObject._unselectable, and
ShieldAddRoleAssignmentPushdown moved to ListItem, the one subclass a $select
serves it for.Folder.content_type_order and unique_content_type_order answer a
ClientValueCollection[ContentTypeId], so a caller reads StringValue off each member.declared_type
can see them — 403 columns. Compare by .name. A value no member names is kept as the
service sent it, and one that differs only in case is that member.ClientValue subclass no longer takes @dataclass: the base class applies
dataclass(cls, repr=False) in __init_subclass__, once per class. A second pass over
fields the first already consumed is a different class. Drop the decorator.if TYPE_CHECKING: block bound are reachable: 145 more columns answer a
type — ListItem.created is datetime, not None. Four cyclic value types still cannot.SP.User loses the 58 profile getters that were a second copy of SP.Directory.User,
plus User.get_user_profile_properties and Web.site_id. The profile fields live on
sharepoint.directory.users.user.User or behind PeopleManager.NavNode and WebNavigation are removed: a captured navigation is the model's own tree,
read through Web.navigation.get_tree(recursive=True).MigrationItem no longer carries author_id/editor_id — they are
item.author.user_id / item.editor.user_id, and the old keywords raise TypeError.
ItemReport keeps both columns.PagePayload is gone (a page item is a SitePage); PAGE_LIBRARY_TEMPLATE,
SITE_PAGE_CONTENT_TYPE_PREFIX and is_modern_page left migration.sharepoint.pages in
favour of is_page_library(list); offline_context() moved to
office365.migration.offline.IcsProfile is IcsDialect, and each family's record is one class with methods:
CalendarEventRecord and its helpers are EventRecord, the contact_* helpers are
ContactRecord, and STANDALONE_EVENT_TYPES/event_kind are gone.office365.permissions, which exports
require_permission, declared, PermissionRequirement, Requirement,
Requirement.join, ResourceName and index. The office365.directory.permissions
modules that held it are gone, and declared(method, flow=...) raises instead of
answering an empty requirement when the method names nothing under that flow. The
package keeps Graph's permission entities, which are model types, not vocabulary.@require_permission(resource=ResourceName.SharePoint, delegated=[...]). A name is only
a grant on the API that defines it, so names from two resources are never merged
(Requirement.join refuses). The default is ResourceName.Graph.office365.sharepoint.workflow.task is gone with the second SPWorkflowTask it
declared; import SP.Workflow.SPWorkflowTask from
office365.sharepoint.workflow.sp_workflow_task.ListItem.moderation_status, SitePage.moderation_status and
UserInfoItem.o_data___moderation_status answer an SPModerationStatusType member
instead of the raw integer, so a comparison against a literal reads false.
SitePage.moderation_status is readonly as well.select_all() is TypeSchema.of(...).columns, expand_all() is .expansions,
select_facet(f) is .columns_of_facet(f) and odata_name(a) is .name_of(a) — on a
ClientValue too.Model metadata
ClientValue.__init_subclass__
runs dataclass(cls, repr=False) and reads the schema from those fields, with
@dataclass_transform() telling a type checker what the decorator said._schema.key
and _schema.versions, from @key(...) and @version(...).@key("tenantId") declares which property spells a type's identity: what re-anchors an
entity's path when the value is set, and what a read forces into $select.__init_subclass__: TypeSchema.of(Model) is an attribute read, with nothing scanned
twice.columns,
navigations, expansions, readonly, persistable, system, beta_names,
canonical_names, beta_only, stable_only and facets.@odata(name="birthday", compare=Compare(format="date")), where Compare carries
casefold and fallback.@odata(navigation=True) marks an $expand-only member and @odata(expandable=False)
one $expand will not follow alone: TypeSchema.of(Event).expansions no longer names
extensions, which the service refuses without a $filter.@odata(system=True) records provenance: the metadata declares no such name, the service
spells it on the item payload.hydrate(payload, profile=None) is the one in-place read verb on ClientObject,
ClientValue and ClientResult, answers self so it chains, and reads what to_json()
writes when no profile is given.JsonProfile.scoped(Model, only=..., without=...) narrows any profile to some properties of
one model, and entity.to_json(COMPARABLE) spells a model in the comparable form
(office365.runtime.odata.comparable), so two copies that differ only by what the service
rewrites compare equal and a real difference does not.office365.runtime.serialization
(JsonSerializable.to_json(profile=None), PropertyReceiver.set_property(...)), and
JsonProfile keeps only what it uses.values_of(cell) answers the items of a collection cell in every shape a read or a
payload produces.ListItem.value_column(name) and string_value_column(name) spell the item columns a
Lookup or Person value travels under: <name>Id, and the read-only <name>StringId.$select column of a served package resolves a declared type, including the twelve
value-object getters that carried no annotation.SharePoint items
ListItem.set_system_metadata(values, new_document_update=False) writes the system fields
of a list item in one ValidateUpdateListItem request: a datetime as ...Z UTC, a
User as its login.ListItem.restore_fidelity(created, modified, author, editor, approval, ...) writes what a
copy of an item cannot carry in its payload — the dates, the authorship, the approval
columns — in one request.SPModerationStatusType spells the approval column's five values, and the three getters
that read the column answer it.Outlook mail
MessageCollection.add_from_mime(data) creates a draft from RFC 822 bytes — an .eml
file as it sits on disk — posting them base64-encoded as text/plain.Migration
migration_client(client) applies the background-workload policy in one call: a shared
RateLimiter on the context's transport, plus x-ms-throttle-priority: low on a Graph
client.IdentityMap maps source principals onto target principals for authorship and ACLs, from
a CSV (source,target[,system_id]), an e-mail domain rewrite or a policy.MailFolderSource and MailExportTarget write one .eml plus
one sidecar per message and a manifest.jsonl index; EmlTreeSource and MailboxTarget
import it back through add_from_mime. A resumed run skips what is on disk, and mail is
verified by mime_digest — the semantic headers plus a hash per decoded part — because
Exchange re-serialises every message it stores. Each family has its options class
(MailExportOptions, MailImportOptions and a matching pair per family).CalendarSource/IcsExportTarget and
ContactSource/VcfExportTarget write one .ics (RFC 5545 folding, TZID, RRULE,
VALARM) or one .vcf plus a sidecar per record, and IcsTreeSource/CalendarTarget
and VcfTreeSource/ContactTarget import them, replaying Graph's own recurrence
object from the sidecar.MigrationItem.metadata carries adapter-defined envelope attributes — a message's
subject, recipients, categories — into the manifest, so a portable export writes its own
index. The runner never interprets it.MigrationJob.plan() states the fidelity forecast before it enumerates
(plan.fidelity, MigrationJob.fidelity(), export_reports), and describe_fidelity
reports a product's own dimensions.sp_list= / structure=) and replays it before
the first write, so a bundle can be imported into a library that has none of its shape.PermissionEntry.principal_type="group", owner, owner_groups), because a <Group>
without an Owner fails the whole ingestion job.FileVersion.sort_key compares version labels as numbers ("1.9" before "1.10"), and
BasePermissions.value / from_value(mask) own the 64-bit permission mask both ways.publishing/pages/fields.py: PAGE_FIELDS,
BODY_FIELDS), and SPBuiltInContentTypeId.SitePage is the content type base a modern
page derives from.UserIdInfo holds
name_id, and ClientValue.set_property / get_property resolve a wire spelling through
the schema, the way to_json already did in the other direction.tests/unit/test_declaration_ratchets.py): $select and $expand never offer the same
name, expansions stays inside navigations, a facet offers only names $select can
carry.Long-running operations
stream() / astream() yield each snapshot,
terminal one last, and raise nothing for a failed outcome. wait() is the same loop with
the failure policy applied.OperationStatus carries the timeline (created_date_time, last_action_date_time
timezone-aware with a UTC fallback, retry_after), and a partiallySucceeded operation is
terminal-but-neither-outcome.RespondAsyncRequest.execute() returns an operation either way: pollable when the service
answered 202, already terminal when it finished in the submitting round-trip
(LongRunningOperationResult.completed(...), is_completed).office365.runtime.operation.Operation): deadline,
Retry-After pacing, jitter, progress hook, cooperative cancel and transient_statuses=
as data.MigrationServerJob.job_wait() returns the wait instead of running it, so polls can be
streamed, cancelled or monitored concurrently.Service limits
quotas module per product (outlook, teams,
onedrive, onedrive.workbooks, reports, security, directory, communications),
each registering itself at import, plus GLOBAL_QUOTAS. Two more modules carry the limits
a migration meets at scale: subscriptions/quotas.py and onenote/quotas.py.CALL_RECORD_QUOTAS, EXCEL_QUOTAS),
and a quota is declared where the request is made — including on the operation that makes
the call.@limit composes: a second decorator on one target adds its rows, and stacked
declarations share one Limits: section. declared_limits() answers each row once, reads
@limit off the MRO, and limits_of(cls) answers class-level rows too._schema; the 25 that are not are
named rather than forgotten.Permissions
office365.migration declare their grant, the 37 SharePoint ones as a @site_access rung
(capture_*/read* are READ, apply_*/provision_* are WRITE). No package is left
to exempt: migration left UNTRACKED, so index(office365).debt() is {} for every
package.@derived_from(callee) stamps a wrapper with the same PermissionRequirement the callee
carries, read once at import, so a pass-through cannot drift from the method it drives.
The request detector now counts execute_query_async and execute_batch_async.office365.permissions.TokenClaims parses a JWT's payload and answers one requirement:
the audience says which API issued it, scp names the delegated permissions, roles the
application ones. The signature is not checked — the token came over TLS.access_token, acquiring it once if they hold none,
so a caller can ask what a token proves before sending a request. A live test's skip
decision reads that token first and the tenant's grants only where the token cannot speak.office365.permissions.catalog(resource) answers what an API publishes —
Catalog.publishes(name, kind), requires_admin_consent(name, kind) and the names
themselves — generated from that API's own service principal.GraphClient (has_/grant_/get_/revoke_, delegated and
application) take resource, defaulting to Microsoft Graph.AllSites.Read → .Write → .Manage →
.FullControl, with Sites.Read.All → .FullControl.All beside them for app-only —
declared on Web and SecurableObject (20 methods), on the everyday objects (File 51,
ListItem 35, ListCollection 5), on Site (70, of which 31 act outside the site
collection) and on every remaining owner.Tenant (284 operations),
SiteMoveService (86) and Office365Tenant (43) name a rung and, where the permission
alone does not decide, the SharePoint Administrator role — 413 declarations. The six page
kinds, the workflow task, all 21 Teams operations, and every Communications, Directory,
OneDrive, tenant-configuration, compliance, social and plumbing operation declare too.office365.permissions exports DirectoryRole, a str enum carrying Entra's own
display name, and @odata(identity=...) lets a type say which members name the object, so
a securable's ACL is read through the type rather than a spelled-out $expand.via
column. An IDE's test runner gets OFFICE365_LIVE=1 in .env as its switch, and nothing
writes .env any more — the wizard that merged its findings back into it is gone.List, Web and the SharePoint
principal types answer the question ListItem, Folder, File, Field, ContentType
and SitePage already did.List's 98 columns are
declared read-only from a write-and-read-back probe, not from a reading of the docs.Web gains 62 read-only declarations, Group 8.facet=AUTHORSHIP,
facet=PERMISSIONS or facet=MODERATION, and TypeSchema.columns_of_facet(...) answers
the columns of that role.filterable, sortable, searchable,
nullable and description are gone from ODataPropertyMeta and @odata(...); not one
of the 4,883 declarations set any of them.records.iter_records derives its columns from the model, so an item carrying an extra
field no longer reorders every header.AuthorId, EditorId, Created,
Modified, FileRef and FileLeafRef are system=True, and is_file / is_folder read
file_system_object_type rather than the presence of something else.is_visible and is_external read
IsVisible/IsExternal, so every node no longer answers None.has_unique_role_assignments is
readonly, and FirstUniqueAncestorSecurableObject and RoleAssignments are navigations.Field answers what a column holds — is_taxonomy, is_lookup, is_person,
is_multi_valued, is_multi_choice, is_value_object — over schema_property(...) and
is_taxonomy_column(...), so a reader need not parse the schema.iso_z and
wall_clock_text for the two date spellings a SharePoint write takes, normalize_guid
over uuid.UUID, and checksum(data).calendar_profile,
calendar_codec, calendar_models), so an enum that gains a member is a table row.(10 s connect, 300 s read), with write and pool bounds on httpx), so a server that stops responding
mid-response fails as a transient error instead of blocking the caller.MigrationJob.plan() fails fast on a fidelity flag the adapter pair cannot honour, one
phase before the first write.LongRunningOperationResult.monitor_url is str | None; the ingestion-job monitor counts
its deadline on the clock; PollableOperation.wait(sleep=None) can be woken by cancel().BaseItem and Permission declare
FILES_QUOTAS, so limits_of(DriveItem) no longer returns nothing while
office365/onedrive/quotas.py publishes nine rows for it.filelock and tornado declares requires-python >=3.11, so a 3.10 lock branch could
only keep a vulnerable pin. The package itself still installs on 3.8.order_by never reached the service. QueryOptions emitted its Python attribute names as
query keys, so a sorted read asked for $order_by — which Graph answers 200 to and
ignores. Every standard option is now spelled as the specification spells it
(order_by → $orderby), and a custom key is still the caller's own.Message.upload_attachment sends anything under 3 MB inline, and that path only
registered a child on the message's attachments collection — a child that rides the
message create.InvalidClientQueryException), so {"results": [...]} is the column's shape.$select read narrowed every later read of the object it was made on:
ReadEntityQuery appended its properties to the object's own query_options.{base}/teams/{alias} was a guess, and this tenant served the site at /sites/TeamSite….SitePage.web_parts
asked for pages/{id}/webParts and the service answered Resource not found for the segment 'webParts'; it asks for pages/{id}/microsoft.graph.sitePage/webParts now.Requirement now asks the committed catalogue.Model
ClientValue fields defaulted to a value instance (trigger: WorkflowExecutionTrigger = WorkflowExecutionTrigger()), so every value ever constructed aliased it; they use
field(default_factory=...)./termStore is served by
SharePoint's own model and answers The specified type named microsoft.graph… is not recognized, with or without the leading #."password,softwareOath", which no member names, so reading a strength policy
raised TypeError. The collection keeps the wire spelling.ChangeTrackedEntity declares
createdDateTime and lastModifiedDateTime readonly, as the CSDL marks them computed.1000000, 1000000 * 3 and 4 MiB.DirectoryRole inherited the base entity_type_name and announced itself as
#microsoft.graph.DirectoryObject.DirectoryRoleCollection.assign failed with no subject: a name with no template left the
lookup None and raised AssertionError from inside a response listener. It raises
ValueError naming the role.Team.messaging_settings read the guest settings, because the getter spelled
guestSettings in its body.SignIn.location read the status: the city, state and country came back empty because the
getter spelled status, the name a neighbouring getter already owned.FileStorageContainer.entity_type_name named no namespace: it answered
graph.fileStorageContainer where every other type name starts with microsoft.graph..visibility: GET /groups/{id} sends Public where GET /teams/{id} sends public.TYPE_CHECKING entry, both invisible to
typing.get_type_hints, so the declaration resolved to None.timedelta column held the ISO string: sixteen columns declare timedelta and
_SCALAR_CONVERTERS had no entry, so a read gave 'PT30M'.ChatInfo and ConditionalAccessGrantControls
cannot be imported at module level, so the getter imports them for itself and
get_type_hints saw a NameError.properties.get.SharingInformation.domain_restriction_settings read the anonymous-link expiry, the name
its neighbour already owned.Runtime
to_json() is 62% faster on a payload of built-in scalars: serialize_value answers a
str, int, bool, float or None before asking whether the value is an object.parse_datetime tries ISO parsing first — 15.6× faster — and still reads a .NET stamp
with seven fractional digits on every supported interpreter.ODataPathBuilder skips a special-character replacement
the value does not contain.Progress is built positionally on the hot path.GET is
what they get.TypeSchema gave five Mapping fields a
default_factory a type checker reads as one shared instance.execute_query_retry
retried on its own backoff and ignored Retry-After.to_json() no longer emits __-prefixed bookkeeping (__etag, __deferred,
__odata_type): they describe the response, not the entity.DateTimeTimeZone.parse() reads what callers pass: a Graph dict, an aware datetime, a
string. A dict used to raise AttributeError, so EventCollection.add(start={...}) was
unusable.str() on a scalar collection renders the list ([freeBusyRead, read]) instead of the
internal type name, and repr() is quoted and type-qualified.200 requests / 24h rather than / 86,400s.SharePoint (client)
List.export() exports files: the loop compared the wire's number against
FileSystemObjectType.File and 0 == File is False.ClientQuery.url pasted the query's own
path onto the service root.FeatureCollection.add(verify_if_activated=True) activates a feature the collection does
not list: the guard asked GetById('<guid>'), which answers null at site scope.Utility.resolve_principal_in_current_context accepts its flags as enums: scopes and
sources are Edm.Int32 bit flags and the call sent the enum's repr.SitePage projection is one the service accepts: TemplateScope answers 400 NotSupported, so the getter declares selectable=False.canvas_content, so TypeSchema.name_of("canvas_content") raised.create_copy_jobs wrapped exportObjectUris in a {"results": [...]} envelope the
service rejects.PeopleManager.get_user_profile_properties
is the reader for UserProfilePropertiesForUser, and Tenant.get_site_subscription_id
raises System.NotSupportedException.SitePageFieldsData(Title="x")
serialises as {"Title": "x"}, not {"Title": "x", "CoAuthState": {}}, so a farm that
never had that property does not refuse the create.Migration (client-side)
Created/Modified dict, another merged the approval dict at two points,
and the library kept its own UTC→local converter with a per-value cache. Both resolve
authors and approval into a pending record and hand it to ListItem.restore_fidelity
once, with web_local_dates=True on the library side.item.file_ref,
is_file, has_unique_role_assignments) instead of the JSON bag.fields read became _source_fields() and the column's own predicates.File.Versions includes
the current version, which the read passed through as an older one.Manifest.xml has no <List>
object, so a list record became a <File> whose content was the record's dict repr.configure() writes nothing, and whatever a structure replay cannot reproduce
is reported on target.warnings.Migration (server-side package path)
commit() submitted a second ingestion job for the same package.Migration (Outlook)
TypeSchema.of(Event).columns, TypeSchema.of(Contact).columns).iCalUId is read as the service spells it: the envelope asked for iCalUid, so every
sidecar carried "ical_uid": null and the .ics UID fell back to the Graph id.repr text: recurrence is flattened
through to_json() instead of reaching json.dumps as a typed value.Permissions
DEVELOPERPACK_E5.--verify could build a
client only for the password and secret flows.ServicePrincipal.get_application_permissions reported a subset of the client's grants: it
read appRoleAssignedTo, which Graph answers truncated even when expanded.ServicePrincipal.grant_application_permissions granted twice, because its idempotency
check read the same truncated collection.ServicePrincipal.get_delegated_permissions answered from one grant: a resource holding a
tenant-wide grant plus per-user ones reported only the first.ServicePrincipal.revoke_delegated_permissions removes the scope from grants on this
resource only, not from every grant of the client app that spells the name./search/query
methods named Files.ReadWrite.--grant died on it:
tests/directory/test_governance.py listed Approve.AppConsentRequests.Read.All beside
EntitlementManagement.Read.All as an any-of.Two stories: the SharePoint migration layer grew from "copy items" to a resumable, verifiable site copy, and the runtime grew async/await, long-runnin
Two stories: the SharePoint migration layer grew from "copy items" to a resumable, verifiable site copy, and the runtime grew async/await, long-running operations and a set of write/lookup primitives that the generated surface lacked.
MigrationSession.add_site_task(...) resolves a migrate_all task into one job per list - each with its own manifest and checkpoint - creates missing target containers and replays each list's structure before content is copied. include_subwebs=True mirrors the source subsite tree.verify() report answers "did this web migrate?" across content, structure, settings, pages and security.MigrationSession.start(concurrency=N) runs list jobs in parallel, each on a context clone sharing the auth context, transport and RateLimiter. The migrate_site.py console now names the list it is on, heartbeats each phase, and closes each list with copied/failures/throughput.execute_query_async, execute_query_parallel_async, execute_batch_async, get_all_async, export_to_async, async beforeExecute and RateLimiter.acquire_async, with an abort path that cancels in-flight siblings. Offloaded by default; a native-async HttpxTransport is available via the [httpx] extra.OperationPoller (Operation-Location / Azure-AsyncOperation / Retry-After, terminal states, continuation tokens, cancel/timeout/progress), the PollableOperation mixin, Prefer: respond-async helpers, and awaitable MigrationServerJob.monitor_async/progress_async/errors_async.BaseTransport.stream/stream_async, File.download_session(-async), bounded-memory export_to, resumable uploads and high-level folder downloads.EntityCollection.upsert, update_all, Entity.update_properties, List.ensure_field/ensure_fields, and ClientRuntimeContext.collect_batch_failures() - a rejected sub-request is recorded against its own query and the rest of the batch still runs, instead of the first failure aborting everything.ThrottleMonitor counts responses, 429/503s and the Retry-After seconds a run waited for (observation only - retry, backoff and pacing are untouched); --pace SECONDS is the proactive lever.The public surface is additive; three modules moved, and the old import paths are gone. Nothing else in this release changes or removes an existing API.
Report calls return the new ReportResult (a ClientResult subclass, so .value, bytes() and .execute_query() behave as before) instead of ClientResult[bytes].office365.security (was office365.discovery.security).TaskStatus lives at office365.todo.tasks.taskstatus (was office365.todo.taskstatus).ListItem.set_property on multi-person columns are all migrated; an empty multi-value column no longer fails verification.Forms/ scaffolding and the auto-provisioned Assets notebook are skipped rather than reported as extra items, and Office Open XML documents are no longer flagged as content mismatches.unverifiable, writes flush and checkpoint per chunk, and conflict_resolution=OVERWRITE reaches record targets.warning and handed it to session.warnings(). They are deduplicated and counted (×12 …) and the CLI reports them once.asyncio.run() no longer fails with RuntimeError: Event loop is closed.SearchService.post_query accepts a sort_list, the same argument the GET form of the query takes; the POST form had no SortList at all, so passing one failed outright.📄 Full changelog: CHANGELOG.md · 📦 pip install --upgrade office365-rest-python-client
Two stories: the SharePoint migration layer grew from "copy items" to a resumable, verifiable site copy, and the runtime grew async/await, long-running operations and a set of write/lookup primitives that the generated surface lacked.
The public surface is additive; three modules moved, and the old import paths are gone. Nothing else in this release changes or removes an existing API.
Report calls return the new ReportResult (a ClientResult subclass, so
.value, bytes() and .execute_query() behave as before) instead of
ClientResult[bytes].office365.security (was
office365.discovery.security).TaskStatus lives at office365.todo.tasks.taskstatus (was
office365.todo.taskstatus).SharePoint migration
MigrationSession.add_site_task(...)
resolves a migrate_all task into one job per list — each with its own manifest
and checkpoint — creating missing target containers and replaying each list's
structure (columns, content types, views, container settings) before content is
copied. include_subwebs=True mirrors the source subsite tree.migrate_site.py console prints a
heartbeat per list ([ 4/24] Documents migrating 412/1,010 (40.8%) 9.7 it/s ETA 1m02s) and a closing line the moment a list finishes (✓ [ 4/24] Documents 1,010 copied 1m42s 9.9 it/s 2.4 MB/s, ! when it left failures); progress counters
are derived per job in both serial and parallel mode (a carried-over rate and total
no longer produce an ETA of hours), the window restarts when the stage changes, a
heartbeat carries its subject, and repeated warnings print once with a count.MigrationSession.start(concurrency=N) runs N list jobs in parallel, each on a
ClientContext clone that shares the auth context, transport and RateLimiter
(adapters are re-addressed with rebind(), since a context owns one
pending-query queue); add_site_task(progress=...) heartbeats the resolution
phase (lists, containers, structure, then pages/navigation/branding)
instead of staying silent. Example flag: --lists-in-flight N.ThrottleMonitor counts responses,
429/503s and the Retry-After seconds a run waited for (observation only:
retry, backoff and pacing are untouched); MigrationSession(throttle=...) logs
throttled events and adds the totals to run.completed. Example flag:
--pace SECONDS, the proactive lever.Title/Description, custom permission levels, web role assignments,
Quick Launch and top navigation, the home-page designation, and modern site
pages plus classic wiki pages are copied. Workflows, InfoPath forms, BCS
external lists, checked-out files and un-published (minor) versions cannot be
produced by a client-side copy, so each is reported instead.TaxonomyFieldType/…Multi) values, multi-choice, hyperlink, multi-value
lookup and person remapping, a content-type identity map (SharePoint assigns
recreated types fresh ids), folder item metadata, list container settings with
approval state, and attribute-level column verification (Required, Indexed,
choices, validation).Runtime
execute_query_async,
execute_query_async_retry, execute_query_parallel_async (with an on_error
collector), execute_batch_async, get_all_async, export_to_async,
retry_async, async beforeExecute, RateLimiter.acquire_async/paced_async,
an abort path that cancels in-flight siblings, contextvars preserved across the
offloaded call, a tunable offload pool, and an optional native-async
HttpxTransport ([httpx] extra).BaseTransport.stream/stream_async,
File.download_session/download_session_async and DriveItem content streams,
DriveItem.resumable_upload_async, bounded-memory export_to, high-level
Folder.download / FileCollection.download.OperationPoller
(Operation-Location / Azure-AsyncOperation / Retry-After, terminal states,
continuation tokens, cancel + timeout + progress hook), the PollableOperation
mixin, LongRunningOperationResult, Prefer: respond-async helpers,
TeamsAsyncOperation.poll_for_status_async, streamed report export, and
awaitable MigrationServerJob.monitor_async/progress_async/errors_async.EntityCollection.upsert (idempotent
create-or-reconcile), EntityCollection.update_all, Entity.update_properties,
Entity.delete_object(ignore_missing=True), List.ensure_field/ensure_fields,
Field.schema_xml_for_copy(), batch $batch writes, and token-aware
Web.get_securable_object.ClientRuntimeContext.collect_batch_failures() runs a
batch tolerantly — a rejected sub-request (denied write, validation error,
retries exhausted) is recorded against its own query as (query, exception) and
the remaining sub-requests still execute, instead of the first failure aborting
the whole batch. Throttled sub-requests are still retried, and the default
outside the scope is unchanged (first failure raises).get_by_* (resolve one) versus find_by_* (return
None), tolerant Graph resolvers, ClientObject.get_or_none(), and a bounded
single().@query_capabilities(...) with
property-level Prefer injection, and a
Prefer: include-unknown-enum-members helper.ClientRuntimeContext.with_auto_retry(...) (inherited by
clones), async token locks and HttpxTransport clients that follow the running
event loop (a transport reused from a second asyncio.run() rebuilt its
AsyncClient; a lock bound to a finished loop is replaced), a typed
AccessDeniedException for 401/403, @require_permission
hints on denied requests, Credential.is_expired/days_until_expiry/
expiry_status, idempotent Application.ensure_certificate,
with_certificate(public_certificate=...) without a thumbprint, idempotent app +
service-principal setup and application-permission grants, async token
callbacks, and Sites.Selected helpers (Site.grant_access).client.domains as a DomainCollection,
RestorePointCollection with a typed search, PlannerTask.assign_to plus
checklists, NotebookCollection.ensure, OneNote pages from in-memory HTML,
ReportResult.to_text()/csv_rows(), AttachmentBase.content_bytes,
readable __str__/__repr__ for runtime objects, and term-store hierarchy
export/import without the payload name clash.verify() reports unexpected target items as such (a new
VerificationReport field) instead of as content mismatches.PlannerEntity: If-Match from the latest etag plus
Prefer: return=representation, so consecutive updates no longer fail with a
stale-token 409.ViewCollection.create/ensure_view annotate view_type as int | str. (The
three moved modules are listed under Breaking in 3.3.0.)Migration (client-side)
Lookup/Person (including the Type="Lookup" Mult="TRUE" spelling),
taxonomy, and ListItem.set_property on multi-person columns are all migrated;
bulk creates adopt the list's entity-type annotation; an empty multi-value
column no longer fails verification.ValidateUpdateListItem and the
timestamp write then repeated the same values, so every preserved item cost two
system updates (three with approval state). The principals are resolved and
cached first and written once — with the timestamps when they are preserved,
otherwise in a single final write before the approval step.unverifiable, writes
flush and checkpoint per chunk, and conflict_resolution=OVERWRITE now reaches
record targets.Forms/ scaffolding and the auto-provisioned
SiteAssets/<web title> Notebook are skipped rather than reported as extra
items, folder system metadata and column values are written, approval state is
carried, and Office Open XML documents are no longer flagged as content
mismatches (SharePoint re-serializes them, so byte equality is unattainable).warning (one of them with
the list name prefixed) and handed it to session.warnings(), so every note
printed twice — once by logging's last-resort handler, once by the caller. They are
DEBUG provenance now; the caller decides how to show them.$batch instead of one request each. A change set is atomic, so a refusal falls
back to writing them one by one — a setting the list type cannot accept is still
its own warning and does not abort the others.ContentType.set_default
works, reorder_fields sends a plain JSON array, FieldLink.field_internal_name
falls back to Name, ContentTypeId declares the right OData type, V3 enums
serialize as Edm.Int32, and the taxonomy TextField round-trips.$batch rounds under collect_batch_failures(), so one round of three
requests replaces the one-per-link exchange that dominated a replay (~35 requests
for a ten-column, five-view list, ~60 % of them links). A refused column is still
reported per column with the server's reason, and the read-back — not the
sub-responses — decides what is linked, because a change set is atomic and one
refusal rolls its siblings back while they answer 200. Link order is restored
per content type only when the target's order differs, so a re-run writes
nothing.Home-2.aspx/Home-3.aspx, ClientContext.clone(url)
no longer sends requests to the original site, a select projection no longer
drops every item value and attachment, manifest/checkpoint saves create their
directory and are crash-safe, a stale error handler no longer swallows later
failures, and structure-provisioning warnings reach session.warnings().Migration (server-side package path)
PermissionEntry carries the system id, display
name, e-mail and role masks; MigrationItem carries author/editor), version
history is carried through MigrationJob, timestamps are emitted as valid XML
dateTime, a single-list task no longer skips structure replay, CreateFieldAsXml
field links are emitted, and UserGroup.xml writes a normalized PUID.Runtime and models
datetime/date/Enum/UUID scalars in dict- and list-built bodies,
reserved-word property declarations, and the concrete OData type for Teams
members, chats (topic) and shared channels, To Do attachments and links, URL
threat assessments, subject-rights dataSubject, change notifications, Intune
role assignments, and Planner assignment/checklist maps.RequestsTransport,
transport-level TLS verification and proxies, httpx per-request NO_TIMEOUT,
batch GETs placed outside the change set, multi-phase SharePoint batch writes,
and list-item creates and updates deferred until the list's entity type is
known (a batched hyperlink or multi-value update used to be sent unannotated and
rejected with A value without a type name was found).ReportResult raw content, Group.created_datetime returning None,
nested OneDrive folder addressing, ensure_folder/ensure_file on a folder
addressed by id, sharing-link expiration dates, webhook expiration format,
$top sent to directoryRoles, sign-in timestamps as datetime, doubled
apostrophes in OData literals, certificate reuse detection in the setup scripts,
naive credential timestamps, has_application_permissions false negatives,
agreement-file inheritance, the device-flow prompt, chat members right after
creation, and examples/onedrive/termstore/export_tree.py.SearchService.post_query accepts sort_list (a list of Sort), the same
argument the GET form query takes; it is sent in the request body as
SortList. A POST that asks for no sorting sends the same body as before.get_by_name / get_by_title / get_by_path helpers
emit a FutureWarning; get_by_* now means "resolve one", find_by_* means
"return None". Removal in v4.SubjectRightsRequestIdentity, the unused MigrationMode enum, and three stale
duplicate model modules.docs/migration.md (plan → copy → verify, with the limits stated),
docs/async.md, docs/long-running-operations.md, and an async section in the
README and the docs reading path.quickstart.py each: SharePoint getting-started, Teams, usage reports, Microsoft
To Do, Intune (with a lifecycle diagram) and Purview, plus an async example
catalog.tests/settings.py and
.env, python -m tests.setup guides the setup, tests/doctor --require checks
a run's prerequisites, applications/rotate_cert.py --generate mints a
self-signed certificate, and OFFICE365_USERNAME / OFFICE365_USERNAME_ALT
replace the two-user test model.--log-level DEBUG in the migration example now prints the run's events as
plain lines (configure_text_logging()), instead of being a no-op without
--log-json.A large release centered on data import/export, large-list reliability, and the SharePoint Migration API.
A large release centered on data import/export, large-list reliability, and the SharePoint Migration API.
ViewXml in Python instead of raw strings: Caml.text("Status").eq("Active"), Caml.lookup("Category").id().in_([2, 3]), binary-nested .and_()/.or_()/.not_(), plus where / order_by / group_by / view_fields.ImportResult queues, executes and discards chunks (bounded memory) with checkpoints (resume interrupted runs), live progress, dead-lettering, and keyed skip/upsert so re-runs never duplicate rows.office365.migration.package (manifest/export XML, PackageBuilder, AES-256-CBC staging, SharePointPackageTarget) and SPMT-style MigrationSession / MigrationServerJob with server-side provisioning and progress. Document-library subset.FileLockedException (.lock_owner, .GUIDANCE) and SPFileCheckOutException, opt-in retry with retry_on(FileLockedException), and bypass_shared_lock=True.Folder.get_files and List.get_items(page_size=...), List.ensure_indexed() (the real fix for #427), typed SPQueryThrottledException, and a one-time warning at the 5,000-item threshold. See docs/large-lists.md.SPFileCheckOutException, SPListDataValidationException, …).DriveItem.ensure_file(), the shared get_or_create helper, and ensure_*(on_conflict="skip"|"update") across fields, lists and content types.from_* is now the streaming entry (returns ImportResult); queue_* is the deferred queue-all path. Removed import_* and to_json_file / from_json_file (use export_to(..., format="json") / from_json); FieldCollection.from_dataframe → ensure_from_dataframe.List.from_dataframe() returns an ImportResult driver (was List); progress is keyword-only.MigrationOptions.preserve_timestamps now defaults to False, and requesting fidelity an adapter pair can't honor raises NotImplementedError instead of silently doing nothing.ensure_* helpers now return the ensured entity/entities.allow_ntlm=True fixed.User.remove_by_id).$skip paging no longer collides with a server $skiptoken.CreateMigrationJobEncrypted sends the key as base64.Name → FileLeafRef).📄 Full changelog: CHANGELOG.md · 📦 pip install --upgrade office365-rest-python-client
FileLockedException (also
SPFileLockedException) parses the lock holder into .lock_owner with remediation
in .GUIDANCE; retry_on(FileLockedException) opts into retrying lock errors, and
delete_object(bypass_shared_lock=True) sends Prefer: bypass-shared-lock on
Graph and SharePoint. See examples/sharepoint/files/handle_locked_file.py.DriveItem.ensure_file(path, content, on_conflict=...) reuses or overwrites the leaf file, creating missing parents.Caml / CamlQuery.builder() build ViewXml from
composable expressions (comparisons, field-typed helpers, Caml.now, logical joins
rendering binary-nested CAML, where/order_by/group_by/row_limit/scope/view_fields);
raw ViewXml/parse remain. New modules under
office365/sharepoint/listitems/caml/.ImportResult — a deferred, source-agnostic streaming import driver with a
sequential, batch, or iterated terminal; ClientObjectCollection.import_records()
and List.from_dataframe().List.import_dataframe(..., key=..., key_field=..., on_conflict="skip"|"upsert") derives SHA-256 keys and skips/updates existing rows
(ImportStats.skipped, enforce_unique, dry_run).ImportResult(checkpoint=...) persists the committed cursor
per chunk; resumed_from/checkpoint/ImportStats.resumed_from expose the offset;
on_error="collect" records a failing chunk and continues.ClientObjectCollection.clear() and a concurrency argument on
Entity.execute_batch().OperationStats shared counter base, specialized by ImportStats/MigrationStats.progress fires immediately (with the resumed offset),
per committed chunk, and per completed batch; run_parallel reports on the calling
thread; execute_batch's success_callback fires per batch in sequential mode;
List.import_from(..., total=...).preserve_timestamps/preserve_permissions
applied client-side via DataSource.read_permissions, DataTarget.apply_timestamps
and apply_permissions(item, permissions) (PermissionEntry).docs/migration.md.Site.provision_migration_containers,
provision_migration_queue, create_migration_job_encrypted, and
get_migration_job_progress; MigrationServerJob.submit_encrypted/progress/
status_fn; parse_progress_events.office365.migration.package): models for
Manifest.xml/ExportSettings.xml/SystemData.xml/UserGroupMap.xml,
PackageBuilder, FileSystemStaging, BlobStaging (new [azure] extra),
create_staging(...), and SharePointPackageTarget. Covers the document-library
subset; the generated XML is not yet live-verified.docs/migration.md covers which legs need
Azure, the Staging seam, and a step-by-step example.BlobStaging/create_staging accept an
encryption_key (AES-256-CBC, unique IV); SharePointPackageTarget forwards it,
and [azure] now also pulls in cryptography.migrate_library_serverside.py and the tenant-free
package_library.py.MigrationSession mirrors the SPMT cmdlets
(register/get/add_task/remove_task/show/start/stop/unregister), with
MigrationSettings, MigrationTask, and a SharePoint resolver (client-side REST or
use_migration_api=True); MigrationOptions gained created_after/modified_after.FileVersions scan — records files with version history, with the SMAT columns.CheckedOutFiles, LargeExcelFiles, BrowserFileHandling,
LongOneDriveUrls, ThicketFolder, and UnsupportedSiteTemplates, sharing a
SiteScanRecord base; WebTemplateType covers the full Get-SpoWebTemplate
catalog; Limits.LARGE_EXCEL_FILE backs the Excel threshold.MATCH_PRIORITY dispatch; ClientRequestException.hresult/.error_type; a
SharePointException catch-all plus typed SPFileCheckOutException,
SPListDataValidationException, SPFieldValidationException,
SPFieldValueException, SPDuplicateValuesFoundException,
SPInvalidLookupValuesException, SPContentTypeReadOnlyException, and
SPContentTypeSealedException.SPFileCheckOutException from the shared-lock FileLockedException (an unresolved
423 still maps to FileLockedException).from_* is the streaming entry (returns
ImportResult) and queue_* the deferred path. Removed import_from/
import_records/import_dataframe/import_from_file and to_json_file/
from_json_file; FieldCollection.from_dataframe → ensure_from_dataframe.RecordCollection
base (inherited by every typed EntityCollection); formats resolve through
runtime.converters.registry; keyed skip/upsert is a pluggable UpsertTarget
implemented by ListItemUpsertTarget.import_from/import_records gained enforce_unique=True and dry_run=True.List gained record facades (import_from/import_dataframe/import_records,
export_to/to_dataframe); List.from_dataframe is now deferred.SharePointListSource reuses the shared record projection.MigrationOptions.preserve_timestamps defaults to False; unhonorable flags raise
NotImplementedError; preserve_versions still needs the server-side Migration API.Site.create_migration_ingestion_job — azure_queue_report_uri/ingestion_task_key
are now optional.export_to(..., page_size=...) streams
appendable formats; with on_error="collect" and a dead_letter, each failing row
is dead-lettered.SPQueryThrottledException; paged
Folder.get_files (refs #930/#936/#462) and List.get_items(query, page_size=...);
List.ensure_indexed/Field.ensure_indexed (the real fix for #427); a warning on
unpaged filter/sort queries; new docs/large-lists.md (including #726).ListItemCollection, FileCollection,
FolderCollection) warn once at the 5,000-item threshold (refs #930/#936);
CamlQuery.index_candidates/List.index_candidates; List.check_query pre-flights
a query.ImportResult.run(...) aliases execute_batch;
ImportResult.verify; a shared VerificationReport (runtime.verification).tsv, parquet, orc and feather
([parquet]), from_sql/to_sql ([sql]), from_duckdb/to_duckdb
([duckdb]); every reader/writer accepts a path, PathLike, or open file.Folder.write_dataframe/File.write_dataframe,
Folder.read_dataframe/File.read_dataframe, and List.from_file; codecs are
dataframe_to_bytes/dataframe_from_bytes.List.import_from(..., schema={column: FieldType})
coerces values into the payload shape; coerce_field_value; generic
RecordCollection.import_from(..., coerce={key: converter}).import_from(..., mapping={...}) renames source columns/keys.RecordCollection.verify_keys(keys) and
List.verify_dataframe(df, key=...).import_from(..., dead_letter="dl.jsonl") appends each
collected chunk failure.List.import_from(..., on_schema_change="evolve"|"fail"),
backed by an ImportResult before_chunk hook.MigrationRunner uses the persisted
Checkpoint.source_watermark to skip and advance.office365/migration/_util.py; helpers moved to runtime.operations,
runtime.converters.scalars, and runtime.converters.json_file. Report writing is
now per-format (write_dataset/write_formats).MigrationItem carries created and author_id/editor_id.ensure_* share
runtime.queries.get_or_create.get_or_create/create_or_get and accept
on_conflict="skip"|"update".List.ensure_field/ensure_fields and FieldCollection.from_dataframe now return
the ensured entities; List.ensure_fields_from_dataframe was removed.List.from_dataframe() returns an ImportResult driver; progress
is keyword-only.FunctionImport whose this is Collection(X) was attached to item class
X; the SharePoint (v3) and Graph (v4) readers now skip them, removing 49 methods
from 24 item classes (e.g. User.remove_by_id, Feature.remove, SubtitleFile.add,
SitePublishingPage.set_multilingual, SiteProperties.get_lock_state_by_id,
MigrationTask.batch_*).AuthenticationContext.authenticate_request when the transport carries a handler
and nothing is configured.SPListItem (live-validated). The
Migration API silently skips an SPFile unless the package also contains its
SPListItem; PackageBuilder.add_file now emits it. Every <User> must carry
SystemId, and DeploymentRoles must not be emitted.PackageBuilder.add_role_assignment now defaults object_type="2". The grant
itself and Author/ModifiedBy still don't land (the target SID isn't exposed by
the SPO REST API; parked).ClientContext(url, allow_ntlm=True)
delegates to AuthenticationContext.with_credentials and forwards
allow_ntlm/browser_mode; the retired-SAML guard still fires for SharePoint Online.SharePointPackageTarget no longer emits an empty ExportSettings SiteUrl.
It resolves the site URL or raises a clear error, and accepts a source_type.Manifest.xml now matches the service shape. It emits the library root
SPFolder, the SPDocumentLibrary, a folder per subfolder and an SPFile per file;
UserGroupMap.xml → UserGroup.xml; the ViewFormsList namespace is fixed.Requirements.xml,
RootObjectMap.xml, LookupListMap.xml, ViewFormsList.xml). Failed jobs are
diagnosable via MigrationServerJob.all_events/errors and
SharePointPackageTarget.events/errors/diagnose.CreateMigrationJobEncrypted sends the AES key as base64 text instead of
decoding it.$skip paging no longer collides with a server $skiptoken.ImportCheckpoint now
records a source signature so a mismatch rescans the source._ suffix and a warning).series_kind/field_type_from_kind handle more kinds and fall back to Text
instead of raising KeyError.A large release: a full migration toolkit (SharePoint / Outlook / Teams) with SMAT-style pre-migration assessment, first-class parallel execution ( ex
A large release: a full migration toolkit (SharePoint / Outlook / Teams)
with SMAT-style pre-migration assessment, first-class parallel execution
(execute_batch / execute_query_parallel), a data pipeline
(CSV/JSON/NDJSON/Excel + optional pandas), and a set of long-standing
SharePoint/OneDrive fixes (#881, #988, #915, #884, #793, #875).
No breaking API changes - a drop-in upgrade from 3.0.0.
sharepoint, outlookteams products: resumable MigrationJob/MigrationSession withMigrationAssessor/MigrationTenantAssessor/MailboxAssessor, typed scanLargeSites, LockedSites, MailFolders) and CSV/JSON export.execute_batch(concurrency=N) on ClientContextGraphClient, plus execute_query_parallel(concurrency=N) forRetry-After.from_csv/from_json/from_records, dynamic list-item columns, and anto_dataframe/from_dataframe).Web.ensure_list, DriveItem.ensure_folder, and typed field creators.ClientContext.clone now shares the auth context and transport.ClientQuery generics madeassess/ → migrate/ → monitor/).File.move_by_path /MoveCopyUtil.move_file_by_path; slashes are no longer percent-encodeddownload_folder paginates children$skip when no next link is returned@odata.type casting for directory collections (#921); principal pathClientRequestException.sharepoint, outlook and
teams: resumable MigrationJob/MigrationSession, filesystem/SharePoint/JSON/
Teams archive adapters, parallel transfer, a server-side ingestion job, and
summary/item/failure reports.MigrationAssessor/MigrationTenantAssessor/MailboxAssessor, typed reports
(LargeSites, LockedSites, MailFolders), and CSV/JSON export.execute_batch(concurrency=N) on ClientContext and
GraphClient, plus execute_query_parallel(concurrency=N); per-request retry
honoring Retry-After.from_csv/from_json/
from_records, dynamic list-item columns, and an optional pandas bridge.Web.ensure_list,
DriveItem.ensure_folder, and typed field creators.ClientContext.clone shares the auth context and transport.ClientQuery generics made consistent.assess/ → migrate/ → monitor/).File.move_by_path/MoveCopyUtil.move_file_by_path; slashes are no
longer percent-encoded inside OData string literals.download_folder paginates children.$skip with no next link
(#915); custom
headers are preserved across pages.@odata.type casting for directory collections
(#921); principal
path precedence (#895);
delta-token/custom query-param handling
(#948); malformed
JSON surfaced as ClientRequestException.office365/runtime/odata to
generator/odata; generator checkpoints are no longer tracked.Use with_username_and_password (MSAL ROPC) instead. ACS App-Only ( with_client_credentials ) is marked deprecated.
First major release in over a year - and it's live on PyPI with an automated release pipeline.
with_user_credentials now raises RuntimeError for SharePoint Online. Use with_username_and_password (MSAL ROPC) instead. ACS App-Only (with_client_credentials) is marked deprecated.with_username_and_password (MSAL ROPC) for SharePoint Online authclient_runtime_context.py / read_entity.pyNameError: name 'List' is not defined in fields/collection.pysingle() and first() return types (never return None)AttributeError: 'str' object has no attribute 'get' when SharePoint returns a string error payload.travis.yml (moved to GitHub Actions)requirements.txt / requirements-dev.txt (use uv/pyproject.toml)pip install --upgrade office365-rest-python-clientOr with uv:
uv pip install --upgrade office365-rest-python-clientfile.serverRelativeUrl → file.server_relative_url). The OData wire keys are unchanged, so properties["ServerRelativeUrl"], get_property(), ensure_property(), and $select/$expand keep working. No aliases shipped: the old names raise AttributeError. Migration guide: Upgrading from 2.xwith_user_credentials now raises RuntimeError for SharePoint Online. Use with_username_and_password (MSAL ROPC) instead. ACS App-Only (with_client_credentials) marked as deprecated.with_username_and_password (MSAL ROPC) for SharePoint Online authSelf, X | None)datetime.utcnow() replaced with timezone-aware alternatives (Python 3.12+ deprecation)entity_type_name support, EnumType generation, template-driven model propsResourceName)client_runtime_context.py / read_entity.pyNameError: name 'List' is not defined in fields/collection.pysingle() and first() return types (never return None)AttributeError: 'str' object has no attribute 'get' when SharePoint returns a string error payload.travis.yml (use GitHub Actions instead)requirements.txt / requirements-dev.txt (use uv/pyproject.toml)uv and pyproject.tomlChangelog #953 : support Access Token Refresh for MSAL Provided Tokens by @kamilkrukowski #956 : resolve get_comments() method issue #958 : added Repl
get_comments() method issueFile.open_binary issue by @bhavberiNothing published for this version
support for Azure environments in ClientContext
ClientContextctx = ClientContext(
site_url, environment=AzureEnvironment.USGovernmentHigh
).with_client_credentials(client_id, client_secret)#950: Username and password authentication (with_user_credentials method): Added support for automatically renewing authentication cookies when the expiration period ends (after 30 minutes)
#926: support for used range has been introduced
ClientContext (USGovernment, GCC High, etc.)with_user_credentials (after 30 min expiry) (#950)Microsoft Search API enhancements
include_resource_data to SubscriptionCollection.add by @optimygmbhChangelog #835 - JSON batch request fixes
#835 - JSON batch request fixes
Changelog #788 - batch request fixes and improvements
#788 - batch request fixes and improvements
Changelog #873 : fix error when creating a choice field #872 : fix shares.by_url method #869 : Bump msal from 1.24.1 to 1.28.0 #627 : Fixes failing dr
shares.by_url methodChangelog #866 : fix path issue when addressing drive items
Changelog #847 Add a note for Entra ID permissions when updating SP metadata fields #850 Fixes issue of str raising exception when DecodeUrl is None #
SharePoint resources addressing enhancements
client = GraphClient.with_token_interactive(
tenant_name_or_id, app_client_id, admin_principal_name
)
resource = client.service_principals.get_by_name("Microsoft Graph")
app = client.applications.get_by_app_id(app_client_id)
resource.grant_application(app, "MailboxSettings.Read").execute_query()client = GraphClient.with_token_interactive(
tenant_name_or_id, app_client_id, admin_principal_name
)
resource = client.service_principals.get_by_name("Microsoft Graph")
app_role = "User.Read.All"
user = client.users.get_by_principal_name(test_user_principal_name)
resource.grant_delegated(app_client_id, user, app_role).execute_query()`python cert_credentials = { "tenant": tenant_name, "client_id": client_id, "thumbprint": cert_thumbprint, "cert_path": "selfsignkeyenc.pem", "passphr
ClientContext.with_client_certificate methodExample:
cert_credentials = {
"tenant": tenant_name,
"client_id": client_id,
"thumbprint": cert_thumbprint,
"cert_path": "selfsignkeyenc.pem",
"passphrase": "Password",
}
ctx = ClientContext(site_url).with_client_certificate(**cert_credentials)
current_web = ctx.web.get().execute_query()
ClientContext.with_client_certificate (#836)Example: create a folder with a color
Example: create a folder with a color
ctx = ClientContext(site_url).with_credentials(user_credentials)
root_folder = ctx.web.default_document_library().root_folder
folder = root_folder.folders.add(
"archive", color_hex=FolderColors.DarkGreen
).execute_query()
```python client = GraphClient.with_username_and_password( tenant_name, client_id, username, password ) drive_item = client.me.drive.root.get_by_path(
Example: get Range
client = GraphClient.with_username_and_password(
tenant_name, client_id, username, password
)
drive_item = client.me.drive.root.get_by_path("Financial Report.xlsx")
worksheets = drive_item.workbook.worksheets.get().execute_query()
if len(worksheets) == 0:
sys.exit("No worksheets found")
worksheet_range = worksheets["Sheet1"].range(address="A1:B3").execute_query()
### Changelog - #794 SharePoint authentication support with GCC High Environments by @DEADSCOP - #802 fix listing folders insted of listing files by @
### Changelog - #791 fix: do not reuse same instance for recipient by @byenilmez - #787 support for file_name parameter in File.copyto and File.copyto
file_name parameter in File.copyto and File.copyto_using_path methodsparent_folder and parent_collection empty when retrieving file using ctx.web.get_file_by_server_relative_urlfile_name parameter to File.copyto and File.copyto_using_path (#787)TypedDict on Python 3.7 (#781)parent_folder / parent_collection empty when retrieving file by server-relative URL (#764)### Changelog - #762: Missing dependency typing_extensions on Python by @chludwig-haufe - #764: file and folder addresing methods fixes - #765: CI & L
## Changelog - #757: Conditionally import ParamSpec from typing_extensions by @thaiphv
ParamSpec from typing_extensions (#757)introduced GraphClient.with_client_secret and GraphClient.with_username_and_password methods to initialize the client, refer below examples
Folder.copy_to_using_path methodmypy and pyright type checkers) by @kellerzaFile.download_session method fixGraphClient.with_client_secret and GraphClient.with_username_and_password methods to initialize the client, refer below examplesGraphClient client using user namename and password flow:from office365.graph_client import GraphClient
client = GraphClient.with_username_and_password(
"contoso.onmicrosoft.com", client_id, username, password
)
GraphClient with client secret:from office365.graph_client import GraphClient
client = GraphClient.with_client_secret("contoso.onmicrosoft.com", client_id, client_secret)
## Changelog - #723: fixes FieldCollection.add_dependent_lookup_field by @pclasen-eb - #722: fixes 404 error with Web.get_file_by_server_relative_path
FieldCollection.add_dependent_lookup_field by @pclasen-ebWeb.get_file_by_server_relative_path methodSupport for Interactive authentication via ClientContext.with_interactive method introduced
ClientContext.with_interactive method introducedClientContext clienttenant = "contoso.onmicrosoft.com"
ctx = ClientContext(site_url).with_interactive(tenant, client_id)
me = ctx.web.current_user.get().execute_query()
print(me.login_name)
When addressing a file or folder, in addition to _server relative url_ format /sites/mysite/folder/filename.ext, it is supported to specify url in _si
When addressing a file or folder, in addition to server relative url format /sites/mysite/folder/filename.ext, it is supported to specify url in site or web relative format now: folder/filename.ext, for example:
ctx = ClientContext(site_url).with_credentials(credentials)
file_url = 'Shared Documents/Report.xlsx'
file = ctx.web.get_file_by_server_relative_url(file_url).get().execute_query()
Use ensure_created method which polls for team status to determine whether it has been created:
client = GraphClient(acquire_token)
new_team = client.teams.create(team_name).ensure_created().execute_query()
## Changelog - #672: Error handling for when response is not present by @akrymskiy - #667: add ability to pass b64 formatted string when adding attach
ClientResult (return type) between calls when passing to execute_query method by @vgremSharePoint API search namespace enhancements
For methods from SharePoint API search namespace those return type contains value pf SimpleDataTable type, cell values getting addressed like this:
for row in results.Table.Rows:
print(row.Cells["Path"]) # prints cell value for `Path` property
Here is an complete example
ctx = ClientContext(site_url).with_credentials(user_credentials)
result = ctx.search.query("contentclass:STS_Site").execute_query()
results = result.value.PrimaryQueryResult.RelevantResults
for row in results.Table.Rows:
print(row.Cells["Path"]) # prints site url
OneDrive enhancements in terms of Excel support
Create a new table example
from office365.graph_client import GraphClient
from office365.onedrive.workbooks.tables.rows.row import WorkbookTableRow
file_name = "Financial Sample.xlsx"
client = GraphClient(acquire_token)
workbook = client.me.drive.root.get_by_path(file_name).workbook
table = workbook.tables.add("A1:C10", True).execute_query()
List rows example
from office365.graph_client import GraphClient
from office365.onedrive.workbooks.tables.rows.row import WorkbookTableRow
file_name = "Financial Sample.xlsx"
client = GraphClient(acquire_token)
workbook = client.me.drive.root.get_by_path(file_name).workbook
table = workbook.worksheets["Sheet1"].tables["financials"].get().execute_query()
print(table.name)
# read table content
rows = table.rows.get().execute_query()
for r in rows: # type: WorkbookTableRow
print(r.values)
enhancements for SharePoint & OneDrive APIs
ClientRuntimeContext.execute_query_retry method by @jneuendorfwith_client_certificate methodcert_path = 'selfsigncert.pem'
with open(cert_path, 'r') as f:
private_key = open(cert_path).read()
cert_credentials = {
'tenant': test_tenant,
'client_id': '--client id--',
'thumbprint': '--thumbprint--',
'private_key': private_key
}
ctx = ClientContext(test_team_site_url).with_client_certificate(**cert_credentials)
field_value = ImageFieldValue(image_url)
list_item.set_property(field_name, field_value).update().execute_query()
introduction of ClientObjectCollection.get_all method to retrieve all the items in a collection, regardless of the size, for example:
ClientObjectCollection.get_all method to retrieve all the items in a collection, regardless of the size, for example:
def print_progress(items):
"""
:type items: office365.sharepoint.listitems.collection.ListItemCollection
"""
print("Items read: {0}".format(len(items)))
page_size = 500
ctx = ClientContext(site_url).with_credentials(client_credentials)
large_list = ctx.web.lists.get_by_title(list_title)
all_items = target_list.items.get_all(page_size, print_progress).execute_query()
ClientObjectCollection.paged methodpage_size = 500
ctx = ClientContext(site_url).with_credentials(client_credentials)
large_list = ctx.web.lists.get_by_title(list_title)
paged_items = large_list.items.paged(page_size, page_loaded=print_progress).get().execute_query()
for index, item in enumerate(paged_items): # type: int, ListItem
print("{0}: {1}".format(index, item.id))
Folder.copy_to_using_path methodbetter support for Sharing namespace in SharePoint API
QueryOptions.build method, kudos to @jjlonemanSharing namespace in SharePoint APISite Designs and Site Scripts in SharePoint APIExample: Share an anonymous access link with view permissions to a file
ctx = ClientContext(site_url).with_credentials(credentials)
file = ctx.web.get_file_by_server_relative_url(file_url)
result = target_file.share_link(SharingLinkKind.AnonymousView).execute_query()
Example: create a new site script that apply a custom theme
ctx = ClientContext(site_url).with_credentials(credentials)
site_script = {
"$schema": "schema.json",
"actions": [
{
"verb": "applyTheme",
"themeName": "Contoso Theme"
}
],
"bindata": {},
"version": 1
}
result = SiteScriptUtility.create_site_script(ctx, "Contoso theme script", "", site_script).execute_query()
ListItem.validate_update_list_item method: setting dates_in_utc as an _optional_ parameter
SharePoint API:
ListItem.validate_update_list_item method: setting dates_in_utc as an optional parameter (#509)Search namespace enhancements #496SearchService.query methodctx = ClientContext(site_url).with_credentials(credentials)
search = SearchService(ctx)
result = search.query("IsDocument:1").execute_query()
SearchService.post_query methodctx = ClientContext(site_url).with_credentials(credentials)
search = SearchService(ctx)
request = SearchRequest(query_text="IsDocument:1",
sort_list=[Sort("LastModifiedTime", 1)],
select_properties=["Path", "LastModifiedTime"],
row_limit=20)
result = search.post_query(request).execute_query()
ListItem introduced support for system metadata update
SharePoint API:
ListItem introduced support for system metadata update (#330)SiteProperies.update method bug fix #480Web.ensure_folder_path method bug fix #452ListItem system updatePrefer ListItem.validate_update_list_item method which supports overriding system metadata,
Here is an example which demonstrates how to update list item system metadata (namely Author and Modified field values):
ctx = ClientContext(site_url).with_credentials(credentials)
list_tasks = ctx.web.lists.get_by_title("Tasks")
items = list_tasks.items.get().top(1).execute_query()
if len(items) == 0:
sys.exit("No items for update found")
item_to_update = items[0] # type: ListItem
author = ctx.web.site_users.get_by_email(user_principal_name)
modified_date = datetime.utcnow() - timedelta(days=3)
result = item_to_update.validate_update_list_item({
"Author": FieldUserValue.from_user(author),
"Modified": modified_date
}).execute_query()
has_any_error = any([item.HasException for item in result.value])
if has_any_error:
print("Item update completed with errors, for details refer 'ErrorMessage' property")
else:
print("Item has been updated successfully")
```python from office365.graph_client import GraphClient from office365.onedrive.driveitems.driveItem import DriveItem
Example:
from office365.graph_client import GraphClient
from office365.onedrive.driveitems.driveItem import DriveItem
def print_download_progress(offset):
print("Downloaded '{0}' bytes...".format(offset))
client = GraphClient(acquire_token_by_username_password)
# # 1. address file by path and get file metadata
file_item = client.me.drive.root.get_by_path("archive/big_buck_bunny.mp4").get().execute_query() # type: DriveItem
# 2 download a large file (chunked file download)
with tempfile.TemporaryDirectory() as local_path:
with open(os.path.join(local_path, file_item.name), 'wb') as local_file:
file_item.download_session(local_file, print_download_progress).execute_query()
print("File '{0}' has been downloaded into {1}".format(file_item.name, local_file.name))
#430: improved support for overriding underlying HTTP request settings(such as proxy and SSL) by @juguerre
#465: SharePoint API: allow passing scopes via certificate authentication method by @theodoriss
Example
from office365.sharepoint.client_context import ClientContext
cert_settings = {
'client_id': '-- app id--',
'thumbprint': "-- cert thumbprint--",
'cert_path': 'mycert.pem'),
'scopes': ['https://contoso.onmicrosoft.com/.default']
}
ctx = ClientContext(test_site_url).with_client_certificate(test_tenant, **cert_settings)
current_web = ctx.web.get().execute_query()
print("{0}".format(current_web.url))
#461: include pytz to install dependency by @Zahlii
Microsoft Graph API: Improved support for delta queries (official docs)
Example: get incremental changes for users
client = GraphClient(acquire_token_func)
changed_users = self.client.users.delta.get().execute_query()
SharePoint API enhanced support for publishing & webhooks namespaces
publishing & webhooks namespacesThe example demonstrates how to create a Site Page
ctx = ClientContext(team_site_url).with_credentials(client_credentials)
new_page = ctx.site_pages.pages.add()
new_page.save_draft(title="My news page")
new_page.publish().execute_query()
The example demonstrates how to create a webhook to SharePoint list:
ctx = ClientContext(site_url).with_credentials(client_credentials)
push_service_url = "https://westeurope0.pushnp.svc.ms/notifications?token=526a9d28-d4ec-45b7-81b9-4e1599524784"
target_list = client.web.lists.get_by_title("Documents")
subscription = target_list.subscriptions.add(push_service_url).execute_query()
where
push_service_url - your service endpoint URL. SharePoint sends an HTTP POST to this endpoint when events occur in the specified resource
Refer Overview of SharePoint webhooks for a details.
Create plannerTask endpoint)from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
plan = ensure_plan(client.me.planner, "My plan")
task = client.planner.tasks.add(title="New task", planId=plan.id).execute_query()
Get MIME content of a message endpoint)The example demonstrates how to download an Outlook message body in MIME format and save into a file:
client = GraphClient(acquire_token_func)
# requires Mail.ReadWrite permission
user = client.users[test_user_principal_name]
messages = user.messages.select(["id"]).top(10).get().execute_query()
with tempfile.TemporaryDirectory() as local_path:
for message in messages: # type: Message
with open(os.path.join(local_path, message.id + ".eml"), 'wb') as local_file:
message.download(local_file).execute_query() # download MIME representation of a message
initial support for Reports API has been introduced
SecurableObject.get_user_effective_permissions de-serializing response bug fixedctx = ClientContext(team_site_url).with_credentials(client_credentials)
version = ctx.web.get_file_by_server_relative_path(file_url).versions.get_by_id(512)
with open(download_path, "wb") as local_file:
file = version.download(local_file).execute_query()
Documentation:
Documentation: ListItem.GetUserEffectivePermissions method
from pprint import pprint
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.permissions.permission_kind import PermissionKind
client = ClientContext(team_site_url).with_credentials(user_credentials)
file_url = "/sites/team/Shared Documents/Guide.docx"
target_user = client.web.site_users.get_by_email(test_user_principal_name_alt)
target_file = client.web.get_file_by_server_relative_path(file_url)
result = target_file.listItemAllFields.get_user_effective_permissions(target_user).execute_query()
pprint(result.value.permission_levels) # print all permission levels
# verify whether user has Reader role to a file
if result.value.has(PermissionKind.OpenItems):
print("User has access to read a file")
Documentation: reportRoot: getOffice365ActivationsUserCounts
import msal
from office365.graph_client import GraphClient
def acquire_token_by_client_credentials():
settings = load_settings()
authority_url = 'https://login.microsoftonline.com/{0}'.format(tenant)
app = msal.ConfidentialClientApplication(
authority=authority_url,
client_id=client_id,
client_credential=client_secret
)
return app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
client = GraphClient(acquire_token_by_client_credentials)
result = client.reports.get_office365_activations_user_counts().execute_query()
Documentation: use the Microsoft Search API to search content in OneDrive and SharePoint
import msal
from office365.graph_client import GraphClient
def acquire_token_by_client_credentials():
settings = load_settings()
authority_url = 'https://login.microsoftonline.com/{0}'.format(tenant)
app = msal.ConfidentialClientApplication(
authority=authority_url,
client_id=client_id,
client_credential=client_secret
)
return app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
client = GraphClient(acquire_token_by_client_credentials)
result = client.search.query("Guide.docx", entity_types=["driveItem"]).execute_query()
Web.get_folder_by_server_relative_path return type fix @sharifhsn
generator module @rikeshtailorWeb.get_folder_by_server_relative_path return type fix @sharifhsna preliminary support for communications API has been introduced
communications API has been introducedtests)Example 1: address folder by path, where archive/2018 is a folder path:
folder_item = client.me.drive.root.get_by_path("archive/2018").get().execute_query() # type: DriveItem
Examples: list all teams
client = GraphClient(acquire_token_by_client_credentials)
teams = client.teams.get_all(["displayName"]).execute_query()
for team in teams: # type: Team
print(team.display_name)
general: compatibility with Python 2.7 (related: #326 & #275)
msal 1.12.0ListItem.update method (related #365)SharePoint API: improved support for a file and folders addressing details
SharePoint API: improved support for a file and folders addressing details
SharePoint API: support for saving taxonomy columns #353
Example: save a single-valued taxonomy field value
ctx = ClientContext(site_url).with_credentials(credentials)
tasks_list = ctx.web.lists.get_by_title("Tasks")
tax_field_value = TaxonomyFieldValue("{term-label}", "{term-guid}")
item_to_create = tasks_list.add_item({
"Title": "New task",
"{tex-column-name}": tax_field_value,
}).execute_query()
Example: save a multi-valued taxonomy field value
ctx = ClientContext(site_url).with_credentials(credentials)
tasks_list = ctx.web.lists.get_by_title("Tasks")
tax_field_value = TaxonomyFieldValue("{term-label}", "{term-guid}")
tax_field_values = TaxonomyFieldValueCollection([tax_field_value])
item_to_create = tasks_list.add_item({
"Title": "New task",
"{tex-column-name}": tax_field_values,
}).execute_query()
API improvements for Fluent interface
SharePoint API improvements: #303 (addressing versions of ListItem), hubsite namespace, File/Folder copy/move operations
ClientObject.get_property() semantics by @kraptorhubsite namespace, File/Folder copy/move operations
def acquire_token_client_credentials():
authority_url = 'https://login.microsoftonline.com/{tenant}'
app = msal.ConfidentialClientApplication(
authority=authority_url,
client_id='{client-id}',
client_credential='{client-secret}'
)
result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
return result
client = GraphClient(acquire_token_client_credentials)
current_user = self.client.users['{user-principal-name}'].get() # 1.1: construct query to retrieve user details
my_drive = self.client.users['{user-principal-name}'].drive.get() # 1.2: construct query to retrieve user's drive
client.execute_batch() # 2: submit a query to the server
improved support for SharePoint API (fields, tenants namespaces)
Summary:
fields, tenants namespaces)Here are a few examples which demonstrate how to create field and set values for a different field types:
Create a multi lookup field:
lookup_field = list.fields.add_lookup_field(title=lookup_field_name,
lookup_list_id=lookup_list.properties['Id'],
lookup_field_name='Title',
allow_multiple_values=True).execute_query()
Set a multi lookup field value
field_value = FieldMultiLookupValue()
field_value.add(FieldLookupValue(lookup_id))
updated = item_to_update.set_property(lookup_field_name, field_value).update().execute_query()
The list of methods (fields namespace):
FieldCollection.add_url_field(title)FieldCollection.add_lookup_field(title, lookup_list_id, lookup_field_name, allow_multiple_values)FieldCollection.add_choice_field(title, values, multiple_values)FieldCollection.create_taxonomy_field(name, ssp_id, term_set_id, anchor_id,field_id, text_field_id, web_id, list_id)The list of methods (tenant namespace):
Tenant.get_site_health_status(site_url)requests_ntlm is included as an optional dependency
requests_ntlm is included as an optional dependencyREADME.md broken links resolvedimprovements for SAML-based claims authentication, kudos to @wreiner for the implementation and @nsmcan for the proposal #297, #272
FileCollection.create_upload_session method by @beliaev-maksim #289adal library to msal as a mandatory dependency #296sharepoint namespace, new types and methods (Tenant, ViewField, ContentType classes)OutlookClient is decommissioned and no longer availableMigration from Azure Active Directory Authentication Library (ADAL) to use the Microsoft Authentication Library (MSAL) library as a _mandatory_ depend
FieldCollection.create_field_as_xml, FieldCollection.create_taxonomy_fieldImproved support for SharePoint API Batch requests
Here is the comparison of two approaches, in the first example update operation is submitted to server per every list item, while in the second one multiple list item update operations are submitted via a since (batch) request:
list_tasks = ctx.web.lists.get_by_title("Tasks")
items = list_tasks.items.get().execute_query() #
for task_id, item in enumerate(items):
task_prefix = str(randint(0, 10000))
item.set_property("Title", f"Task {task_prefix}")
item.update()
ctx.execute_query() # <- update operation is submitted to server per every list item
list_tasks = ctx.web.lists.get_by_title("Tasks")
items = list_tasks.items.get().execute_query()
for task_id, item in enumerate(items):
task_prefix = str(randint(0, 10000))
item.set_property("Title", f"Task {task_prefix}")
item.update()
ctx.execute_batch() # <- construct a single (batch) for all list items and submit to server
list = client.web.lists.get_by_title(list_title)
list.delete_object()
client.execute_query()
list delete operation could be constructed and submitted to a server in a more compact manner:
client.web.lists.get_by_title(list_title).delete_object().execute_query()
SharePoint API Changes namespace improvements (#259), here is the list of operations:
Site.get_changesWeb.get_changesList.get_changesListItem.get_changesSharePoint API RecycleBin entity class and operations
Finally the initial support for SharePoint API Batch requests has been introduced. All insert/update/delete operations are supported.
Finally the initial support for SharePoint API Batch requests has been introduced. All insert/update/delete operations are supported.
The following example how current user and web objects could be retrieved by grouping two operations and submitting it as a single request to the server:
client = ClientContext(site_url).with_credentials(user_credentials)
current_user = client.web.currentUser
client.load(current_user)
current_web = client.web
client.load(current_web)
client.execute_batch()
which offers a new way of improving the performance.
Among another improvements and changes:
improved support for Office365 auth with ADFS by @liuliqiu
style enforcement (flake8), code formatting (isort) configuration by @domdinicola
ClientRuntimeContext.execute_query_retry method which implements Retry pattern
``` ctx = ClientContext(settings['url']).with_credentials(credentials)
ctx = ClientContext(settings['url']).with_credentials(credentials)
target_web = ctx.web.load().execute_query() #method chaining
print(target_web.url)
Web and File resources by absolute Urlabs_file_url = "https://{tenant}.sharepoint.com/sites/team/Shared Documents/sample.docx".format(tenant=tenant)
user_credentials = UserCredential(username, password)
with open(local_path, 'wb') as local_file:
file = File.from_url(abs_file_url).with_credentials(user_credentials).download(local_file).execute_query()
print("'{0}' file has been downloaded".format(file.serverRelativeUrl))
According to Documentation
Search in SharePoint includes a Search REST service you can use to add search functionality to your client and mobile applications by using any technology that supports REST web requests.
Example
The following example demonstrates how to construct a search for a documents (via Keyword Query Language syntax) and print file url (Path managed property)
from office365.runtime.auth.userCredential import UserCredential
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.search.searchRequest import SearchRequest
from office365.sharepoint.search.searchService import SearchService
from settings import settings
ctx = ClientContext.connect_with_credentials(site_url,
UserCredential(username, password))
search = SearchService(ctx)
request = SearchRequest("IsDocument:1")
result = search.post_query(request)
ctx.execute_query()
relevant_results = result.PrimaryQueryResult.RelevantResults
for i in relevant_results['Table']['Rows']:
cells = relevant_results['Table']['Rows'][i]['Cells']
print(cells[6]['Value'])
The following example demonstrates how to create a site collection via Tenant.CreateSite method:
admin_site_url = "https://{0}-admin.sharepoint.com/".format(tenant)
credentials = UserCredential(username, password)
client = ClientContext(admin_site_url).with_credentials(credentials)
tenant = Tenant(client)
props = SiteCreationProperties(target_site_url, user_principal_name)
site_props = tenant.ensure_site(props)
client.execute_query()
Creating list item and setting multi lookup field value:
create_info = {
"Title": "New task"
}
multi_lookup_value = FieldMultiLookupValue()
multi_lookup_value.add(FieldLookupValue(lookup_id))
new_item = self.target_list.add_item(create_info)
new_item.set_property("Predecessors", multi_lookup_value)
client.load(items)
client.execute_query()
Updating list item with multi choice field value:
multi_choice_value = FieldMultiChoiceValue(["In Progress"])
item_to_update.set_property("TaskStatuses", multi_choice_value)
item_to_update.update()
client.execute_query()
#210: connect to Office 365 with federated accounts, credit goes to @liuliqiu
#206: SharePoint Session API upload
initial support for Microsoft Teams API
and more
The support for Microsoft Teams API has been introduced, the following example demonstrates how how create a new team under a group which corresponds to Create team endpoint
tenant_name = "contoso.onmicrosoft.com"
client = GraphClient(tenant_name, get_token)
new_team = client.groups[group_id].add_team()
client.execute_query()
where
def get_token(auth_ctx):
"""Acquire token via client credential flow (ADAL Python library is utilized)
:type auth_ctx: adal.AuthenticationContext
"""
token = auth_ctx.acquire_token_with_client_credentials(
"https://graph.microsoft.com",
client_id,
client_secret)
return token
Here is an example which demonstrates how to retrieve data from a SharePoint list which contains more then 5k items:
def print_progress(items_read):
print("Items read: {0}".format(items_read))
ctx = ClientContext.connect_with_credentials(site_url,
ClientCredential(client_id,client_secret))
list_source = ctx.web.lists.get_by_title("Contacts_Large")
items = list_source.items
items.page_loaded += print_progress # page load event
items.page_size = 400 # specify custom page size (default is 100)
ctx.load(items)
ctx.execute_query()
#print("Items count: {0}".format(len(items)))
for item in items:
print("{0}".format(item.properties['Title']))
The example demonstrates how to connect to SharePoint Online with certificate credentials:
ctx = ClientContext.connect_with_certificate(site_url,
client_id,
thumbprint,
certificate_path)
current_web = ctx.web
ctx.load(current_web)
ctx.execute_query()
print("{0}".format(current_web.url))
Refer how-to page for a more details
In terms of file and folder operations the following methods have been introduced:
File.download(file_object) - download a file content into a file object (SharePoint API)Folder.copyto(new_folder_url, overwrite) - copy a folder (SharePoint API)Folder.moveto(new_folder_url, flags) move a folder (SharePoint API)DriveItem.download(file_object) - downloads a file content into a file object (OneDrive API)DriveItem.get_content() - downloads a file content (OneDrive API)Now for user credentials flow, instead of
Now for user credentials flow, instead of
ctx_auth = AuthenticationContext(url=site_url)
ctx_auth.acquire_token_for_user(username,password):
ctx = ClientContext(site_url, ctx_auth)
an authenticated client could be initialized like this:
ctx = ClientContext.connect_with_credentials(site_url, UserCredential(username,password))
and for client credentials flow (aka SharePoint App-Only) instead of
ctx_auth = AuthenticationContext(url=site_url)
ctx_auth.acquire_token_for_app(client_id,client_secret):
ctx = ClientContext(site_url, ctx_auth)
like this:
ctx = ClientContext.connect_with_credentials(site_url, ClientCredential(client_id,client_secret))
GroupSiteManager.create_group_ex - create a Team site
SPSiteManager.create - create a Communication site
Create a Team Site
client = ClientContext.connect_with_credentials(url,ClientCredential(client_id,client_secret))
site_manager = GroupSiteManager(client)
info = site_manager.create_group_ex("Team Site", "teamsite", True, None)
client.execute_query()
Create a Communication site
client = ClientContext.connect_with_credentials(url,ClientCredential(client_id,client_secret))
site_manager = SPSiteManager(client)
request = SPSiteCreationRequest("CommSite", "https://contoso.sharepoint.com/sites/commsite")
response = site_manager.create(request)
client.execute_query()
Nothing published for this version
Nothing published for this version
GraphClient client has been introduced for working with Microsoft Graph endpoint
Release changes:
GraphClient client has been introduced for working with Microsoft Graph endpointintroduced support for Introduced support for SharePoint 2010 list data service, ListDataService class
introduced support for Introduced support for SharePoint 2010 list data service, ListDataService class
added methods and properties for List, ListItem and Field resources:
ListItem.validate_update_listItem method - Validates and sets the values of the specified collection of fields for the list item.ListItem.system_update methodListItem.update_overwrite_version methodListItem.parent_list navigation propertyList.fields navigation propertyFieldCollection.add methodFieldCollection.get_by_id methodFieldCollection.get_by_internal_name_or_title methodFieldCollection.get_by_title methodField.update methodField.delete methodAdded support for NTLM authentication #110
Added support for NTLM authentication #110
Switch context per web #111
All the credit goes to @Aisbergg for those changes!
Outlook client transitioned from Office 365 Outlook REST API to Microsoft Graph-based Outlook REST API
Outlook client transitioned from Office 365 Outlook REST API to Microsoft Graph-based Outlook REST API
introduced support for for Resource Owner Password Credential (ROPC) flow, which is suitable for scenarios where BasicAuth (discontinued nowadays) was utilized before
Introduced support for SharePoint authentication via OAuth (app principal) and SharePoint CAML queries
Introduced support for SharePoint authentication via OAuth (app principal) and SharePoint CAML queries
Nothing published for this version
One column per quarter.