Code Monkey home page Code Monkey logo

Comments (6)

parthea avatar parthea commented on June 1, 2024

Hi @theRocket,

The x-goog-fieldmask request header can be set via the metadata argument of PlacesClient.get_place() which is used for adding custom request headers. For example,

    # Make the request
    response = client.get_place(request=request, metadata[("x-goog-fieldmask", "id,displayName")])

The format of the value for x-goog-fieldmask header should be the same as shown in the REST docs here, for example when using curl.

curl -X GET -H 'Content-Type: application/json' \
-H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: id,displayName" \
https://places.googleapis.com/v1/places/ChIJWyLAeY-jhVQRJXqchdJTMio

class PlacesClient(metaclass=PlacesClientMeta):
"""Service definition for the Places API. Note: every request actually
requires a field mask set outside of the request proto (all/'*' is
not assumed). That can be set via either a side channel
(SystemParameterContext) over RPC, or a header (X-Goog-FieldMask)
over HTTP. See: https://cloud.google.com/apis/docs/system-parameters

def get_place(
self,
request: Optional[Union[places_service.GetPlaceRequest, dict]] = None,
*,
name: Optional[str] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = (),

metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.

from google-cloud-python.

theRocket avatar theRocket commented on June 1, 2024

Thank you, @parthea! I was getting close to that solution, but the guess & check was frustrating me. Here is the final code snippet that works:

    # Initialize request argument(s)
    request = places_v1.GetPlaceRequest(
        name="places/ChIJWyLAeY-jhVQRJXqchdJTMio",
    )
    fieldMask = "formattedAddress,displayName"

    # Make the request
    response = client.get_place(request=request, metadata=[("x-goog-fieldmask",fieldMask)])

from google-cloud-python.

theRocket avatar theRocket commented on June 1, 2024

Another issue with SearchNearbyRequest being very obtuse about proper inputs. Can you help, @parthea? Several attempts at this in various data type constructs have failed:

home_loc = [48.7588228,-122.4634339]

def sample_search_nearby(api_key, lat_lng = home_loc, rad=10.0):
    # Create a client
    options = ClientOptions(api_key=api_key)
    client = places_v1.PlacesClient(client_options=options)

    # Initialize request argument(s)
    search_km = 1000*rad # convert from km to meters, max 50000
    search_circle = places_v1.types.Circle(center=lat_lng, radius=search_km)
    loc_restriction = places_v1.SearchNearbyRequest.LocationRestriction(search_circle)

    request = places_v1.SearchNearbyRequest(
        location_restriction=loc_restriction,
        included_types=['electric_vehicle_charging_station']
    )
    fieldMask = "*" # still required
    # Make the request
    response = client.search_nearby(request=request, metadata=[("x-goog-fieldmask",fieldMask)])

Error response:

  File "/Users/ricker/Code/GCP/google-cloud-python/packages/google-maps-places/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py", line 50, in sample_search_nearby
    search_circle = places_v1.types.Circle(center=lat_lng, radius=search_km)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ricker/.pyvenv/gcp-env/lib/python3.12/site-packages/proto/message.py", line 604, in __init__
    super().__setattr__("_pb", self._meta.pb(**params))
                               ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Message must be initialized with a dict: google.maps.places.v1.Circle

This is a required field and the google.maps.places_v1.types.geometry.Circle type signature suggests I have initialized it correctly. I tried also passing a dictionary but received the same error.

If I try something closer to the original sample:

    loc_restriction = places_v1.SearchNearbyRequest.LocationRestriction()
    loc_restriction.circle = places_v1.Circle()
    loc_restriction.circle.center = lat_lng
    loc_restriction.circle.radius = search_km

I still get this must be initialized with a dict error.

from google-cloud-python.

theRocket avatar theRocket commented on June 1, 2024

Sorry, I took one more stab and found the right construct. It is a dictionary for LatLng:

home_loc = {'latitude':48.7649179, 'longitude':-122.4602791}

def sample_search_nearby(api_key, lat_lng = home_loc, rad=10.0):
    ...
    # Initialize request argument(s)
    search_km = 1000*rad # convert from km to meters, max 50000
    loc_restriction = places_v1.SearchNearbyRequest.LocationRestriction()
    loc_restriction.circle = places_v1.Circle(center=home_loc, radius=search_km)

from google-cloud-python.

talksik avatar talksik commented on June 1, 2024

Same problem in https://github.com/googleapis/google-cloud-go

Really confusing telling someone to adjust headers somehow when the SDK initializes a RestClient for you.

from google-cloud-python.

theRocket avatar theRocket commented on June 1, 2024

Same problem in https://github.com/googleapis/google-cloud-go

I suspect because these are both generated clients from the same Protobuf implementation.

Regarding programming languages, Google appears to attempting to solve the primary problem of writing language-agnostic code only once so consumers can use whatever flavor of the month from the following list:

However, making the use of these clients in a well-documented, human understandable way (i.e. developer friendly) seems to be a secondary concern. Perhaps they expect AI to be writing all the code to consume their APIs in the near future.

from google-cloud-python.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.