Python调用Google Sheet API报错:TypeError: request()接收到意外参数'json'
Hey there, let's work through this error you're hitting when trying to access your Google Sheet. That TypeError usually pops up due to version mismatches between the libraries you're using and the code from older tutorials—let's break down the most likely fixes:
1. Check if you're using the gspread library (the most common culprit here)
Your code client.open("Copy of Legislators 2017").sheet1 looks like it's using the gspread library (a popular wrapper for the Google Sheets API), not the official Google API client directly. Here's how to resolve version conflicts:
Upgrade gspread and auth libraries
Outdated versions of gspread often clash with newer Google auth libraries, leading to this exact error. Run these commands to get the latest compatible versions:pip uninstall gspread google-auth google-auth-oauthlib -y pip install gspread google-auth google-auth-oauthlib --upgradeUpdate your authorization code
If you're still using the deprecatedoauth2clientlibrary for auth (common in older tutorials), switch to the supportedgoogle-authmethod. Replace your auth code with something like this:from google.oauth2.service_account import Credentials import gspread # Define the scope for your Google Sheet access SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] # Path to your service account key file CREDS_FILE = 'path/to/your/service-account-key.json' # Create credentials and authorize the gspread client creds = Credentials.from_service_account_file(CREDS_FILE, scopes=SCOPES) client = gspread.authorize(creds) # Now try accessing your sheet again sheet = client.open("Copy of Legislators 2017").sheet1
2. If you're using the official Google Sheets API client
If you meant to use the official google-api-python-client instead of gspread, your code syntax is off. The official API doesn't use client.open()—you'll need to reference the spreadsheet by its ID instead. Here's a quick example:
from google.oauth2.service_account import Credentials from googleapiclient.discovery import build SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SPREADSHEET_ID = 'your-spreadsheet-id-here' # Find this in your sheet's URL creds = Credentials.from_service_account_file('path/to/key.json', scopes=SCOPES) service = build('sheets', 'v4', credentials=creds) # Access the first sheet (Sheet1) sheet_data = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range='Sheet1').execute()
Why this error happens
The request() got an unexpected keyword argument 'json' message means that somewhere in the library code, a request function is being called with a json parameter it doesn't recognize. This almost always stems from version mismatches between core auth libraries (like google-auth) and the Sheets API wrapper (gspread or the official client). Upgrading to compatible versions fixes the parameter mismatch.
内容的提问来源于stack exchange,提问作者Flávio Mendes

