google-developer-knowledge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. google/developer_knowledge/__init__.py +49 -0
  2. google/developer_knowledge/gapic_version.py +16 -0
  3. google/developer_knowledge/py.typed +2 -0
  4. google/developer_knowledge_v1/__init__.py +135 -0
  5. google/developer_knowledge_v1/gapic_metadata.json +73 -0
  6. google/developer_knowledge_v1/gapic_version.py +16 -0
  7. google/developer_knowledge_v1/py.typed +2 -0
  8. google/developer_knowledge_v1/services/__init__.py +15 -0
  9. google/developer_knowledge_v1/services/developer_knowledge/__init__.py +22 -0
  10. google/developer_knowledge_v1/services/developer_knowledge/async_client.py +642 -0
  11. google/developer_knowledge_v1/services/developer_knowledge/client.py +1067 -0
  12. google/developer_knowledge_v1/services/developer_knowledge/pagers.py +201 -0
  13. google/developer_knowledge_v1/services/developer_knowledge/transports/__init__.py +36 -0
  14. google/developer_knowledge_v1/services/developer_knowledge/transports/base.py +227 -0
  15. google/developer_knowledge_v1/services/developer_knowledge/transports/grpc.py +449 -0
  16. google/developer_knowledge_v1/services/developer_knowledge/transports/grpc_asyncio.py +502 -0
  17. google/developer_knowledge_v1/services/developer_knowledge/transports/rest.py +855 -0
  18. google/developer_knowledge_v1/services/developer_knowledge/transports/rest_base.py +236 -0
  19. google/developer_knowledge_v1/types/__init__.py +36 -0
  20. google/developer_knowledge_v1/types/developerknowledge.py +413 -0
  21. google_developer_knowledge-0.1.0.dist-info/METADATA +240 -0
  22. google_developer_knowledge-0.1.0.dist-info/RECORD +25 -0
  23. google_developer_knowledge-0.1.0.dist-info/WHEEL +5 -0
  24. google_developer_knowledge-0.1.0.dist-info/licenses/LICENSE +202 -0
  25. google_developer_knowledge-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1067 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2026 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ import json
17
+ import logging as std_logging
18
+ import os
19
+ import re
20
+ import warnings
21
+ from collections import OrderedDict
22
+ from http import HTTPStatus
23
+ from typing import (
24
+ Callable,
25
+ Dict,
26
+ Mapping,
27
+ MutableMapping,
28
+ MutableSequence,
29
+ Optional,
30
+ Sequence,
31
+ Tuple,
32
+ Type,
33
+ Union,
34
+ cast,
35
+ )
36
+
37
+ import google.protobuf
38
+ from google.api_core import client_options as client_options_lib
39
+ from google.api_core import exceptions as core_exceptions
40
+ from google.api_core import gapic_v1
41
+ from google.api_core import retry as retries
42
+ from google.auth import credentials as ga_credentials # type: ignore
43
+ from google.auth.exceptions import MutualTLSChannelError # type: ignore
44
+ from google.auth.transport import mtls # type: ignore
45
+ from google.auth.transport.grpc import SslCredentials # type: ignore
46
+ from google.oauth2 import service_account # type: ignore
47
+
48
+ from google.developer_knowledge_v1 import gapic_version as package_version
49
+
50
+ try:
51
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
52
+ except AttributeError: # pragma: NO COVER
53
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
54
+
55
+ try:
56
+ from google.api_core import client_logging # type: ignore
57
+
58
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
59
+ except ImportError: # pragma: NO COVER
60
+ CLIENT_LOGGING_SUPPORTED = False
61
+
62
+ _LOGGER = std_logging.getLogger(__name__)
63
+
64
+ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
65
+
66
+ from google.developer_knowledge_v1.services.developer_knowledge import pagers
67
+ from google.developer_knowledge_v1.types import developerknowledge
68
+
69
+ from .transports.base import DEFAULT_CLIENT_INFO, DeveloperKnowledgeTransport
70
+ from .transports.grpc import DeveloperKnowledgeGrpcTransport
71
+ from .transports.grpc_asyncio import DeveloperKnowledgeGrpcAsyncIOTransport
72
+ from .transports.rest import DeveloperKnowledgeRestTransport
73
+
74
+
75
+ class DeveloperKnowledgeClientMeta(type):
76
+ """Metaclass for the DeveloperKnowledge client.
77
+
78
+ This provides class-level methods for building and retrieving
79
+ support objects (e.g. transport) without polluting the client instance
80
+ objects.
81
+ """
82
+
83
+ _transport_registry = OrderedDict() # type: Dict[str, Type[DeveloperKnowledgeTransport]]
84
+ _transport_registry["grpc"] = DeveloperKnowledgeGrpcTransport
85
+ _transport_registry["grpc_asyncio"] = DeveloperKnowledgeGrpcAsyncIOTransport
86
+ _transport_registry["rest"] = DeveloperKnowledgeRestTransport
87
+
88
+ def get_transport_class(
89
+ cls,
90
+ label: Optional[str] = None,
91
+ ) -> Type[DeveloperKnowledgeTransport]:
92
+ """Returns an appropriate transport class.
93
+
94
+ Args:
95
+ label: The name of the desired transport. If none is
96
+ provided, then the first transport in the registry is used.
97
+
98
+ Returns:
99
+ The transport class to use.
100
+ """
101
+ # If a specific transport is requested, return that one.
102
+ if label:
103
+ return cls._transport_registry[label]
104
+
105
+ # No transport is requested; return the default (that is, the first one
106
+ # in the dictionary).
107
+ return next(iter(cls._transport_registry.values()))
108
+
109
+
110
+ class DeveloperKnowledgeClient(metaclass=DeveloperKnowledgeClientMeta):
111
+ """The Developer Knowledge API provides programmatic access to Google's
112
+ public developer documentation, enabling you to integrate this
113
+ knowledge base into your own applications and workflows.
114
+
115
+ The API is designed to be the canonical source for machine-readable
116
+ access to Google's developer documentation.
117
+
118
+ A typical use case is to first use
119
+ [DeveloperKnowledge.SearchDocumentChunks][google.developers.knowledge.v1.DeveloperKnowledge.SearchDocumentChunks]
120
+ to find relevant page URIs based on a query, and then use
121
+ [DeveloperKnowledge.GetDocument][google.developers.knowledge.v1.DeveloperKnowledge.GetDocument]
122
+ or
123
+ [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments]
124
+ to fetch the full content of the top results.
125
+
126
+ All document content is provided in Markdown format.
127
+ """
128
+
129
+ @staticmethod
130
+ def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]:
131
+ """Converts api endpoint to mTLS endpoint.
132
+
133
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
134
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
135
+ Args:
136
+ api_endpoint (Optional[str]): the api endpoint to convert.
137
+ Returns:
138
+ Optional[str]: converted mTLS api endpoint.
139
+ """
140
+ if not api_endpoint:
141
+ return api_endpoint
142
+
143
+ mtls_endpoint_re = re.compile(
144
+ r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
145
+ )
146
+
147
+ m = mtls_endpoint_re.match(api_endpoint)
148
+ if m is None:
149
+ # Could not parse api_endpoint; return as-is.
150
+ return api_endpoint
151
+
152
+ name, mtls, sandbox, googledomain = m.groups()
153
+ if mtls or not googledomain:
154
+ return api_endpoint
155
+
156
+ if sandbox:
157
+ return api_endpoint.replace(
158
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
159
+ )
160
+
161
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
162
+
163
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
164
+ DEFAULT_ENDPOINT = "developerknowledge.googleapis.com"
165
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
166
+ DEFAULT_ENDPOINT
167
+ )
168
+
169
+ _DEFAULT_ENDPOINT_TEMPLATE = "developerknowledge.{UNIVERSE_DOMAIN}"
170
+ _DEFAULT_UNIVERSE = "googleapis.com"
171
+
172
+ @staticmethod
173
+ def _use_client_cert_effective():
174
+ """Returns whether client certificate should be used for mTLS if the
175
+ google-auth version supports should_use_client_cert automatic mTLS enablement.
176
+
177
+ Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var.
178
+
179
+ Returns:
180
+ bool: whether client certificate should be used for mTLS
181
+ Raises:
182
+ ValueError: (If using a version of google-auth without should_use_client_cert and
183
+ GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.)
184
+ """
185
+ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement
186
+ if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER
187
+ return mtls.should_use_client_cert()
188
+ else: # pragma: NO COVER
189
+ # if unsupported, fallback to reading from env var
190
+ use_client_cert_str = os.getenv(
191
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
192
+ ).lower()
193
+ if use_client_cert_str not in ("true", "false"):
194
+ raise ValueError(
195
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be"
196
+ " either `true` or `false`"
197
+ )
198
+ return use_client_cert_str == "true"
199
+
200
+ @classmethod
201
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
202
+ """Creates an instance of this client using the provided credentials
203
+ info.
204
+
205
+ Args:
206
+ info (dict): The service account private key info.
207
+ args: Additional arguments to pass to the constructor.
208
+ kwargs: Additional arguments to pass to the constructor.
209
+
210
+ Returns:
211
+ DeveloperKnowledgeClient: The constructed client.
212
+ """
213
+ credentials = service_account.Credentials.from_service_account_info(info)
214
+ kwargs["credentials"] = credentials
215
+ return cls(*args, **kwargs)
216
+
217
+ @classmethod
218
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
219
+ """Creates an instance of this client using the provided credentials
220
+ file.
221
+
222
+ Args:
223
+ filename (str): The path to the service account private key json
224
+ file.
225
+ args: Additional arguments to pass to the constructor.
226
+ kwargs: Additional arguments to pass to the constructor.
227
+
228
+ Returns:
229
+ DeveloperKnowledgeClient: The constructed client.
230
+ """
231
+ credentials = service_account.Credentials.from_service_account_file(filename)
232
+ kwargs["credentials"] = credentials
233
+ return cls(*args, **kwargs)
234
+
235
+ from_service_account_json = from_service_account_file
236
+
237
+ @property
238
+ def transport(self) -> DeveloperKnowledgeTransport:
239
+ """Returns the transport used by the client instance.
240
+
241
+ Returns:
242
+ DeveloperKnowledgeTransport: The transport used by the client
243
+ instance.
244
+ """
245
+ return self._transport
246
+
247
+ @staticmethod
248
+ def document_path(
249
+ document: str,
250
+ ) -> str:
251
+ """Returns a fully-qualified document string."""
252
+ return "documents/{document}".format(
253
+ document=document,
254
+ )
255
+
256
+ @staticmethod
257
+ def parse_document_path(path: str) -> Dict[str, str]:
258
+ """Parses a document path into its component segments."""
259
+ m = re.match(r"^documents/(?P<document>.+?)$", path)
260
+ return m.groupdict() if m else {}
261
+
262
+ @staticmethod
263
+ def common_billing_account_path(
264
+ billing_account: str,
265
+ ) -> str:
266
+ """Returns a fully-qualified billing_account string."""
267
+ return "billingAccounts/{billing_account}".format(
268
+ billing_account=billing_account,
269
+ )
270
+
271
+ @staticmethod
272
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
273
+ """Parse a billing_account path into its component segments."""
274
+ m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
275
+ return m.groupdict() if m else {}
276
+
277
+ @staticmethod
278
+ def common_folder_path(
279
+ folder: str,
280
+ ) -> str:
281
+ """Returns a fully-qualified folder string."""
282
+ return "folders/{folder}".format(
283
+ folder=folder,
284
+ )
285
+
286
+ @staticmethod
287
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
288
+ """Parse a folder path into its component segments."""
289
+ m = re.match(r"^folders/(?P<folder>.+?)$", path)
290
+ return m.groupdict() if m else {}
291
+
292
+ @staticmethod
293
+ def common_organization_path(
294
+ organization: str,
295
+ ) -> str:
296
+ """Returns a fully-qualified organization string."""
297
+ return "organizations/{organization}".format(
298
+ organization=organization,
299
+ )
300
+
301
+ @staticmethod
302
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
303
+ """Parse a organization path into its component segments."""
304
+ m = re.match(r"^organizations/(?P<organization>.+?)$", path)
305
+ return m.groupdict() if m else {}
306
+
307
+ @staticmethod
308
+ def common_project_path(
309
+ project: str,
310
+ ) -> str:
311
+ """Returns a fully-qualified project string."""
312
+ return "projects/{project}".format(
313
+ project=project,
314
+ )
315
+
316
+ @staticmethod
317
+ def parse_common_project_path(path: str) -> Dict[str, str]:
318
+ """Parse a project path into its component segments."""
319
+ m = re.match(r"^projects/(?P<project>.+?)$", path)
320
+ return m.groupdict() if m else {}
321
+
322
+ @staticmethod
323
+ def common_location_path(
324
+ project: str,
325
+ location: str,
326
+ ) -> str:
327
+ """Returns a fully-qualified location string."""
328
+ return "projects/{project}/locations/{location}".format(
329
+ project=project,
330
+ location=location,
331
+ )
332
+
333
+ @staticmethod
334
+ def parse_common_location_path(path: str) -> Dict[str, str]:
335
+ """Parse a location path into its component segments."""
336
+ m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
337
+ return m.groupdict() if m else {}
338
+
339
+ @classmethod
340
+ def get_mtls_endpoint_and_cert_source(
341
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
342
+ ):
343
+ """Deprecated. Return the API endpoint and client cert source for mutual TLS.
344
+
345
+ The client cert source is determined in the following order:
346
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
347
+ client cert source is None.
348
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
349
+ default client cert source exists, use the default one; otherwise the client cert
350
+ source is None.
351
+
352
+ The API endpoint is determined in the following order:
353
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
354
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
355
+ default mTLS endpoint; if the environment variable is "never", use the default API
356
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
357
+ use the default API endpoint.
358
+
359
+ More details can be found at https://google.aip.dev/auth/4114.
360
+
361
+ Args:
362
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
363
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
364
+ in this method.
365
+
366
+ Returns:
367
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
368
+ client cert source to use.
369
+
370
+ Raises:
371
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
372
+ """
373
+
374
+ warnings.warn(
375
+ "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
376
+ DeprecationWarning,
377
+ )
378
+ if client_options is None:
379
+ client_options = client_options_lib.ClientOptions()
380
+ use_client_cert = DeveloperKnowledgeClient._use_client_cert_effective()
381
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
382
+ if use_mtls_endpoint not in ("auto", "never", "always"):
383
+ raise MutualTLSChannelError(
384
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
385
+ )
386
+
387
+ # Figure out the client cert source to use.
388
+ client_cert_source = None
389
+ if use_client_cert:
390
+ if client_options.client_cert_source:
391
+ client_cert_source = client_options.client_cert_source
392
+ elif mtls.has_default_client_cert_source():
393
+ client_cert_source = mtls.default_client_cert_source()
394
+
395
+ # Figure out which api endpoint to use.
396
+ if client_options.api_endpoint is not None:
397
+ api_endpoint = client_options.api_endpoint
398
+ elif use_mtls_endpoint == "always" or (
399
+ use_mtls_endpoint == "auto" and client_cert_source
400
+ ):
401
+ api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
402
+ else:
403
+ api_endpoint = cls.DEFAULT_ENDPOINT
404
+
405
+ return api_endpoint, client_cert_source
406
+
407
+ @staticmethod
408
+ def _read_environment_variables():
409
+ """Returns the environment variables used by the client.
410
+
411
+ Returns:
412
+ Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
413
+ GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
414
+
415
+ Raises:
416
+ ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
417
+ any of ["true", "false"].
418
+ google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
419
+ is not any of ["auto", "never", "always"].
420
+ """
421
+ use_client_cert = DeveloperKnowledgeClient._use_client_cert_effective()
422
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
423
+ universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
424
+ if use_mtls_endpoint not in ("auto", "never", "always"):
425
+ raise MutualTLSChannelError(
426
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
427
+ )
428
+ return use_client_cert, use_mtls_endpoint, universe_domain_env
429
+
430
+ @staticmethod
431
+ def _get_client_cert_source(provided_cert_source, use_cert_flag):
432
+ """Return the client cert source to be used by the client.
433
+
434
+ Args:
435
+ provided_cert_source (bytes): The client certificate source provided.
436
+ use_cert_flag (bool): A flag indicating whether to use the client certificate.
437
+
438
+ Returns:
439
+ bytes or None: The client cert source to be used by the client.
440
+ """
441
+ client_cert_source = None
442
+ if use_cert_flag:
443
+ if provided_cert_source:
444
+ client_cert_source = provided_cert_source
445
+ elif mtls.has_default_client_cert_source():
446
+ client_cert_source = mtls.default_client_cert_source()
447
+ return client_cert_source
448
+
449
+ @staticmethod
450
+ def _get_api_endpoint(
451
+ api_override, client_cert_source, universe_domain, use_mtls_endpoint
452
+ ) -> str:
453
+ """Return the API endpoint used by the client.
454
+
455
+ Args:
456
+ api_override (str): The API endpoint override. If specified, this is always
457
+ the return value of this function and the other arguments are not used.
458
+ client_cert_source (bytes): The client certificate source used by the client.
459
+ universe_domain (str): The universe domain used by the client.
460
+ use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
461
+ Possible values are "always", "auto", or "never".
462
+
463
+ Returns:
464
+ str: The API endpoint to be used by the client.
465
+ """
466
+ if api_override is not None:
467
+ api_endpoint = api_override
468
+ elif use_mtls_endpoint == "always" or (
469
+ use_mtls_endpoint == "auto" and client_cert_source
470
+ ):
471
+ _default_universe = DeveloperKnowledgeClient._DEFAULT_UNIVERSE
472
+ if universe_domain != _default_universe:
473
+ raise MutualTLSChannelError(
474
+ f"mTLS is not supported in any universe other than {_default_universe}."
475
+ )
476
+ api_endpoint = DeveloperKnowledgeClient.DEFAULT_MTLS_ENDPOINT
477
+ else:
478
+ api_endpoint = DeveloperKnowledgeClient._DEFAULT_ENDPOINT_TEMPLATE.format(
479
+ UNIVERSE_DOMAIN=universe_domain
480
+ )
481
+ return api_endpoint
482
+
483
+ @staticmethod
484
+ def _get_universe_domain(
485
+ client_universe_domain: Optional[str], universe_domain_env: Optional[str]
486
+ ) -> str:
487
+ """Return the universe domain used by the client.
488
+
489
+ Args:
490
+ client_universe_domain (Optional[str]): The universe domain configured via the client options.
491
+ universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
492
+
493
+ Returns:
494
+ str: The universe domain to be used by the client.
495
+
496
+ Raises:
497
+ ValueError: If the universe domain is an empty string.
498
+ """
499
+ universe_domain = DeveloperKnowledgeClient._DEFAULT_UNIVERSE
500
+ if client_universe_domain is not None:
501
+ universe_domain = client_universe_domain
502
+ elif universe_domain_env is not None:
503
+ universe_domain = universe_domain_env
504
+ if len(universe_domain.strip()) == 0:
505
+ raise ValueError("Universe Domain cannot be an empty string.")
506
+ return universe_domain
507
+
508
+ def _validate_universe_domain(self):
509
+ """Validates client's and credentials' universe domains are consistent.
510
+
511
+ Returns:
512
+ bool: True iff the configured universe domain is valid.
513
+
514
+ Raises:
515
+ ValueError: If the configured universe domain is not valid.
516
+ """
517
+
518
+ # NOTE (b/349488459): universe validation is disabled until further notice.
519
+ return True
520
+
521
+ def _add_cred_info_for_auth_errors(
522
+ self, error: core_exceptions.GoogleAPICallError
523
+ ) -> None:
524
+ """Adds credential info string to error details for 401/403/404 errors.
525
+
526
+ Args:
527
+ error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info.
528
+ """
529
+ if error.code not in [
530
+ HTTPStatus.UNAUTHORIZED,
531
+ HTTPStatus.FORBIDDEN,
532
+ HTTPStatus.NOT_FOUND,
533
+ ]:
534
+ return
535
+
536
+ cred = self._transport._credentials
537
+
538
+ # get_cred_info is only available in google-auth>=2.35.0
539
+ if not hasattr(cred, "get_cred_info"):
540
+ return
541
+
542
+ # ignore the type check since pypy test fails when get_cred_info
543
+ # is not available
544
+ cred_info = cred.get_cred_info() # type: ignore
545
+ if cred_info and hasattr(error._details, "append"):
546
+ error._details.append(json.dumps(cred_info))
547
+
548
+ @property
549
+ def api_endpoint(self) -> str:
550
+ """Return the API endpoint used by the client instance.
551
+
552
+ Returns:
553
+ str: The API endpoint used by the client instance.
554
+ """
555
+ return self._api_endpoint
556
+
557
+ @property
558
+ def universe_domain(self) -> str:
559
+ """Return the universe domain used by the client instance.
560
+
561
+ Returns:
562
+ str: The universe domain used by the client instance.
563
+ """
564
+ return self._universe_domain
565
+
566
+ def __init__(
567
+ self,
568
+ *,
569
+ credentials: Optional[ga_credentials.Credentials] = None,
570
+ transport: Optional[
571
+ Union[
572
+ str,
573
+ DeveloperKnowledgeTransport,
574
+ Callable[..., DeveloperKnowledgeTransport],
575
+ ]
576
+ ] = None,
577
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
578
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
579
+ ) -> None:
580
+ """Instantiates the developer knowledge client.
581
+
582
+ Args:
583
+ credentials (Optional[google.auth.credentials.Credentials]): The
584
+ authorization credentials to attach to requests. These
585
+ credentials identify the application to the service; if none
586
+ are specified, the client will attempt to ascertain the
587
+ credentials from the environment.
588
+ transport (Optional[Union[str,DeveloperKnowledgeTransport,Callable[..., DeveloperKnowledgeTransport]]]):
589
+ The transport to use, or a Callable that constructs and returns a new transport.
590
+ If a Callable is given, it will be called with the same set of initialization
591
+ arguments as used in the DeveloperKnowledgeTransport constructor.
592
+ If set to None, a transport is chosen automatically.
593
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
594
+ Custom options for the client.
595
+
596
+ 1. The ``api_endpoint`` property can be used to override the
597
+ default endpoint provided by the client when ``transport`` is
598
+ not explicitly provided. Only if this property is not set and
599
+ ``transport`` was not explicitly provided, the endpoint is
600
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
601
+ variable, which have one of the following values:
602
+ "always" (always use the default mTLS endpoint), "never" (always
603
+ use the default regular endpoint) and "auto" (auto-switch to the
604
+ default mTLS endpoint if client certificate is present; this is
605
+ the default value).
606
+
607
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
608
+ is "true", then the ``client_cert_source`` property can be used
609
+ to provide a client certificate for mTLS transport. If
610
+ not provided, the default SSL client certificate will be used if
611
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
612
+ set, no client certificate will be used.
613
+
614
+ 3. The ``universe_domain`` property can be used to override the
615
+ default "googleapis.com" universe. Note that the ``api_endpoint``
616
+ property still takes precedence; and ``universe_domain`` is
617
+ currently not supported for mTLS.
618
+
619
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
620
+ The client info used to send a user-agent string along with
621
+ API requests. If ``None``, then default info will be used.
622
+ Generally, you only need to set this if you're developing
623
+ your own client library.
624
+
625
+ Raises:
626
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
627
+ creation failed for any reason.
628
+ """
629
+ self._client_options = client_options
630
+ if isinstance(self._client_options, dict):
631
+ self._client_options = client_options_lib.from_dict(self._client_options)
632
+ if self._client_options is None:
633
+ self._client_options = client_options_lib.ClientOptions()
634
+ self._client_options = cast(
635
+ client_options_lib.ClientOptions, self._client_options
636
+ )
637
+
638
+ universe_domain_opt = getattr(self._client_options, "universe_domain", None)
639
+
640
+ self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = (
641
+ DeveloperKnowledgeClient._read_environment_variables()
642
+ )
643
+ self._client_cert_source = DeveloperKnowledgeClient._get_client_cert_source(
644
+ self._client_options.client_cert_source, self._use_client_cert
645
+ )
646
+ self._universe_domain = DeveloperKnowledgeClient._get_universe_domain(
647
+ universe_domain_opt, self._universe_domain_env
648
+ )
649
+ self._api_endpoint: str = "" # updated below, depending on `transport`
650
+
651
+ # Initialize the universe domain validation.
652
+ self._is_universe_domain_valid = False
653
+
654
+ if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
655
+ # Setup logging.
656
+ client_logging.initialize_logging()
657
+
658
+ api_key_value = getattr(self._client_options, "api_key", None)
659
+ if api_key_value and credentials:
660
+ raise ValueError(
661
+ "client_options.api_key and credentials are mutually exclusive"
662
+ )
663
+
664
+ # Save or instantiate the transport.
665
+ # Ordinarily, we provide the transport, but allowing a custom transport
666
+ # instance provides an extensibility point for unusual situations.
667
+ transport_provided = isinstance(transport, DeveloperKnowledgeTransport)
668
+ if transport_provided:
669
+ # transport is a DeveloperKnowledgeTransport instance.
670
+ if credentials or self._client_options.credentials_file or api_key_value:
671
+ raise ValueError(
672
+ "When providing a transport instance, "
673
+ "provide its credentials directly."
674
+ )
675
+ if self._client_options.scopes:
676
+ raise ValueError(
677
+ "When providing a transport instance, provide its scopes directly."
678
+ )
679
+ self._transport = cast(DeveloperKnowledgeTransport, transport)
680
+ self._api_endpoint = self._transport.host
681
+
682
+ self._api_endpoint = (
683
+ self._api_endpoint
684
+ or DeveloperKnowledgeClient._get_api_endpoint(
685
+ self._client_options.api_endpoint,
686
+ self._client_cert_source,
687
+ self._universe_domain,
688
+ self._use_mtls_endpoint,
689
+ )
690
+ )
691
+
692
+ if not transport_provided:
693
+ import google.auth._default # type: ignore
694
+
695
+ if api_key_value and hasattr(
696
+ google.auth._default, "get_api_key_credentials"
697
+ ):
698
+ credentials = google.auth._default.get_api_key_credentials(
699
+ api_key_value
700
+ )
701
+
702
+ transport_init: Union[
703
+ Type[DeveloperKnowledgeTransport],
704
+ Callable[..., DeveloperKnowledgeTransport],
705
+ ] = (
706
+ DeveloperKnowledgeClient.get_transport_class(transport)
707
+ if isinstance(transport, str) or transport is None
708
+ else cast(Callable[..., DeveloperKnowledgeTransport], transport)
709
+ )
710
+ # initialize with the provided callable or the passed in class
711
+ self._transport = transport_init(
712
+ credentials=credentials,
713
+ credentials_file=self._client_options.credentials_file,
714
+ host=self._api_endpoint,
715
+ scopes=self._client_options.scopes,
716
+ client_cert_source_for_mtls=self._client_cert_source,
717
+ quota_project_id=self._client_options.quota_project_id,
718
+ client_info=client_info,
719
+ always_use_jwt_access=True,
720
+ api_audience=self._client_options.api_audience,
721
+ )
722
+
723
+ if "async" not in str(self._transport):
724
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
725
+ std_logging.DEBUG
726
+ ): # pragma: NO COVER
727
+ _LOGGER.debug(
728
+ "Created client `google.developers.knowledge_v1.DeveloperKnowledgeClient`.",
729
+ extra={
730
+ "serviceName": "google.developers.knowledge.v1.DeveloperKnowledge",
731
+ "universeDomain": getattr(
732
+ self._transport._credentials, "universe_domain", ""
733
+ ),
734
+ "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
735
+ "credentialsInfo": getattr(
736
+ self.transport._credentials, "get_cred_info", lambda: None
737
+ )(),
738
+ }
739
+ if hasattr(self._transport, "_credentials")
740
+ else {
741
+ "serviceName": "google.developers.knowledge.v1.DeveloperKnowledge",
742
+ "credentialsType": None,
743
+ },
744
+ )
745
+
746
+ def search_document_chunks(
747
+ self,
748
+ request: Optional[
749
+ Union[developerknowledge.SearchDocumentChunksRequest, dict]
750
+ ] = None,
751
+ *,
752
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
753
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
754
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
755
+ ) -> pagers.SearchDocumentChunksPager:
756
+ r"""Searches for developer knowledge across Google's developer
757
+ documentation. Returns
758
+ [DocumentChunk][google.developers.knowledge.v1.DocumentChunk]s
759
+ based on the user's query. There may be many chunks from the
760
+ same [Document][google.developers.knowledge.v1.Document]. To
761
+ retrieve full documents, use
762
+ [DeveloperKnowledge.GetDocument][google.developers.knowledge.v1.DeveloperKnowledge.GetDocument]
763
+ or
764
+ [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments]
765
+ with the
766
+ [DocumentChunk.parent][google.developers.knowledge.v1.DocumentChunk.parent]
767
+ returned in the
768
+ [SearchDocumentChunksResponse.results][google.developers.knowledge.v1.SearchDocumentChunksResponse.results].
769
+
770
+ .. code-block:: python
771
+
772
+ # This snippet has been automatically generated and should be regarded as a
773
+ # code template only.
774
+ # It will require modifications to work:
775
+ # - It may require correct/in-range values for request initialization.
776
+ # - It may require specifying regional endpoints when creating the service
777
+ # client as shown in:
778
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
779
+ from google import developer_knowledge_v1
780
+
781
+ def sample_search_document_chunks():
782
+ # Create a client
783
+ client = developer_knowledge_v1.DeveloperKnowledgeClient()
784
+
785
+ # Initialize request argument(s)
786
+ request = developer_knowledge_v1.SearchDocumentChunksRequest(
787
+ query="query_value",
788
+ )
789
+
790
+ # Make the request
791
+ page_result = client.search_document_chunks(request=request)
792
+
793
+ # Handle the response
794
+ for response in page_result:
795
+ print(response)
796
+
797
+ Args:
798
+ request (Union[google.developer_knowledge_v1.types.SearchDocumentChunksRequest, dict]):
799
+ The request object. Request message for
800
+ [DeveloperKnowledge.SearchDocumentChunks][google.developers.knowledge.v1.DeveloperKnowledge.SearchDocumentChunks].
801
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
802
+ should be retried.
803
+ timeout (float): The timeout for this request.
804
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
805
+ sent along with the request as metadata. Normally, each value must be of type `str`,
806
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
807
+ be of type `bytes`.
808
+
809
+ Returns:
810
+ google.developer_knowledge_v1.services.developer_knowledge.pagers.SearchDocumentChunksPager:
811
+ Response message for
812
+ [DeveloperKnowledge.SearchDocumentChunks][google.developers.knowledge.v1.DeveloperKnowledge.SearchDocumentChunks].
813
+
814
+ Iterating over this object will yield results and
815
+ resolve additional pages automatically.
816
+
817
+ """
818
+ # Create or coerce a protobuf request object.
819
+ # - Use the request object if provided (there's no risk of modifying the input as
820
+ # there are no flattened fields), or create one.
821
+ if not isinstance(request, developerknowledge.SearchDocumentChunksRequest):
822
+ request = developerknowledge.SearchDocumentChunksRequest(request)
823
+
824
+ # Wrap the RPC method; this adds retry and timeout information,
825
+ # and friendly error handling.
826
+ rpc = self._transport._wrapped_methods[self._transport.search_document_chunks]
827
+
828
+ # Validate the universe domain.
829
+ self._validate_universe_domain()
830
+
831
+ # Send the request.
832
+ response = rpc(
833
+ request,
834
+ retry=retry,
835
+ timeout=timeout,
836
+ metadata=metadata,
837
+ )
838
+
839
+ # This method is paged; wrap the response in a pager, which provides
840
+ # an `__iter__` convenience method.
841
+ response = pagers.SearchDocumentChunksPager(
842
+ method=rpc,
843
+ request=request,
844
+ response=response,
845
+ retry=retry,
846
+ timeout=timeout,
847
+ metadata=metadata,
848
+ )
849
+
850
+ # Done; return the response.
851
+ return response
852
+
853
+ def get_document(
854
+ self,
855
+ request: Optional[Union[developerknowledge.GetDocumentRequest, dict]] = None,
856
+ *,
857
+ name: Optional[str] = None,
858
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
859
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
860
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
861
+ ) -> developerknowledge.Document:
862
+ r"""Retrieves a single document with its full Markdown
863
+ content.
864
+
865
+ .. code-block:: python
866
+
867
+ # This snippet has been automatically generated and should be regarded as a
868
+ # code template only.
869
+ # It will require modifications to work:
870
+ # - It may require correct/in-range values for request initialization.
871
+ # - It may require specifying regional endpoints when creating the service
872
+ # client as shown in:
873
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
874
+ from google import developer_knowledge_v1
875
+
876
+ def sample_get_document():
877
+ # Create a client
878
+ client = developer_knowledge_v1.DeveloperKnowledgeClient()
879
+
880
+ # Initialize request argument(s)
881
+ request = developer_knowledge_v1.GetDocumentRequest(
882
+ name="name_value",
883
+ )
884
+
885
+ # Make the request
886
+ response = client.get_document(request=request)
887
+
888
+ # Handle the response
889
+ print(response)
890
+
891
+ Args:
892
+ request (Union[google.developer_knowledge_v1.types.GetDocumentRequest, dict]):
893
+ The request object. Request message for
894
+ [DeveloperKnowledge.GetDocument][google.developers.knowledge.v1.DeveloperKnowledge.GetDocument].
895
+ name (str):
896
+ Required. Specifies the name of the document to
897
+ retrieve. Format: ``documents/{uri_without_scheme}``
898
+ Example:
899
+ ``documents/docs.cloud.google.com/storage/docs/creating-buckets``
900
+
901
+ This corresponds to the ``name`` field
902
+ on the ``request`` instance; if ``request`` is provided, this
903
+ should not be set.
904
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
905
+ should be retried.
906
+ timeout (float): The timeout for this request.
907
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
908
+ sent along with the request as metadata. Normally, each value must be of type `str`,
909
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
910
+ be of type `bytes`.
911
+
912
+ Returns:
913
+ google.developer_knowledge_v1.types.Document:
914
+ A Document represents a piece of
915
+ content from the Developer Knowledge
916
+ corpus.
917
+
918
+ """
919
+ # Create or coerce a protobuf request object.
920
+ # - Quick check: If we got a request object, we should *not* have
921
+ # gotten any keyword arguments that map to the request.
922
+ flattened_params = [name]
923
+ has_flattened_params = (
924
+ len([param for param in flattened_params if param is not None]) > 0
925
+ )
926
+ if request is not None and has_flattened_params:
927
+ raise ValueError(
928
+ "If the `request` argument is set, then none of "
929
+ "the individual field arguments should be set."
930
+ )
931
+
932
+ # - Use the request object if provided (there's no risk of modifying the input as
933
+ # there are no flattened fields), or create one.
934
+ if not isinstance(request, developerknowledge.GetDocumentRequest):
935
+ request = developerknowledge.GetDocumentRequest(request)
936
+ # If we have keyword arguments corresponding to fields on the
937
+ # request, apply these.
938
+ if name is not None:
939
+ request.name = name
940
+
941
+ # Wrap the RPC method; this adds retry and timeout information,
942
+ # and friendly error handling.
943
+ rpc = self._transport._wrapped_methods[self._transport.get_document]
944
+
945
+ # Certain fields should be provided within the metadata header;
946
+ # add these here.
947
+ metadata = tuple(metadata) + (
948
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
949
+ )
950
+
951
+ # Validate the universe domain.
952
+ self._validate_universe_domain()
953
+
954
+ # Send the request.
955
+ response = rpc(
956
+ request,
957
+ retry=retry,
958
+ timeout=timeout,
959
+ metadata=metadata,
960
+ )
961
+
962
+ # Done; return the response.
963
+ return response
964
+
965
+ def batch_get_documents(
966
+ self,
967
+ request: Optional[
968
+ Union[developerknowledge.BatchGetDocumentsRequest, dict]
969
+ ] = None,
970
+ *,
971
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
972
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
973
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
974
+ ) -> developerknowledge.BatchGetDocumentsResponse:
975
+ r"""Retrieves multiple documents, each with its full
976
+ Markdown content.
977
+
978
+ .. code-block:: python
979
+
980
+ # This snippet has been automatically generated and should be regarded as a
981
+ # code template only.
982
+ # It will require modifications to work:
983
+ # - It may require correct/in-range values for request initialization.
984
+ # - It may require specifying regional endpoints when creating the service
985
+ # client as shown in:
986
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
987
+ from google import developer_knowledge_v1
988
+
989
+ def sample_batch_get_documents():
990
+ # Create a client
991
+ client = developer_knowledge_v1.DeveloperKnowledgeClient()
992
+
993
+ # Initialize request argument(s)
994
+ request = developer_knowledge_v1.BatchGetDocumentsRequest(
995
+ names=['names_value1', 'names_value2'],
996
+ )
997
+
998
+ # Make the request
999
+ response = client.batch_get_documents(request=request)
1000
+
1001
+ # Handle the response
1002
+ print(response)
1003
+
1004
+ Args:
1005
+ request (Union[google.developer_knowledge_v1.types.BatchGetDocumentsRequest, dict]):
1006
+ The request object. Request message for
1007
+ [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments].
1008
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1009
+ should be retried.
1010
+ timeout (float): The timeout for this request.
1011
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1012
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1013
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1014
+ be of type `bytes`.
1015
+
1016
+ Returns:
1017
+ google.developer_knowledge_v1.types.BatchGetDocumentsResponse:
1018
+ Response message for
1019
+ [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments].
1020
+
1021
+ """
1022
+ # Create or coerce a protobuf request object.
1023
+ # - Use the request object if provided (there's no risk of modifying the input as
1024
+ # there are no flattened fields), or create one.
1025
+ if not isinstance(request, developerknowledge.BatchGetDocumentsRequest):
1026
+ request = developerknowledge.BatchGetDocumentsRequest(request)
1027
+
1028
+ # Wrap the RPC method; this adds retry and timeout information,
1029
+ # and friendly error handling.
1030
+ rpc = self._transport._wrapped_methods[self._transport.batch_get_documents]
1031
+
1032
+ # Validate the universe domain.
1033
+ self._validate_universe_domain()
1034
+
1035
+ # Send the request.
1036
+ response = rpc(
1037
+ request,
1038
+ retry=retry,
1039
+ timeout=timeout,
1040
+ metadata=metadata,
1041
+ )
1042
+
1043
+ # Done; return the response.
1044
+ return response
1045
+
1046
+ def __enter__(self) -> "DeveloperKnowledgeClient":
1047
+ return self
1048
+
1049
+ def __exit__(self, type, value, traceback):
1050
+ """Releases underlying transport's resources.
1051
+
1052
+ .. warning::
1053
+ ONLY use as a context manager if the transport is NOT shared
1054
+ with other clients! Exiting the with block will CLOSE the transport
1055
+ and may cause errors in other clients!
1056
+ """
1057
+ self.transport.close()
1058
+
1059
+
1060
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1061
+ gapic_version=package_version.__version__
1062
+ )
1063
+
1064
+ if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
1065
+ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
1066
+
1067
+ __all__ = ("DeveloperKnowledgeClient",)