如何调用google api 进行开发(使用免费版本)
1.前置条件:
- 有一个你自己的谷歌账户
- 打开这个网页:https://aistudio.google.com/projects
- step up:
- Project/ Create a new project
- set your Project name / ensure your name and "create Project"
- API key -> Create a new key-> set your project
- success
PS:官方文档详见:https://ai.google.dev/gemini-api/docs/quickstart
2. 环境安装
-
安装
conda环境,可以参考:Anaconda超详细安装教程(Windows环境下) -
(cmd)创建虚拟环境并进入对应的虚拟环境
conda create -n google python==3.10
然后全部回车就行
conda activate google
![image-20260415214636523]()
-
安装依赖:
pip install -q -U google-genai -
安装依赖完毕
-
3.设置api
-
打开环境变量设置:
如果找不到搜索框可以从控制面板进入,同样搜索环境变量即可
- 复制你的
api-key
- 构造环境变量:
变量名:
GEMINI_API_KEY
Linux系统自己搜一下修改环境变量吧 - 复制你的
4. 调用google服务(文本输入输出)
from google import genai# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()#这里的model需要google ai stdio上看看有没有额度,有额度就可以用,但是不能直接复制,找到免费的模型后,在https://ai.google.dev/gemini-api/docs/models?hl=zh-cn 找到他的模型代码【Model code】,复制这个才有用
response = client.models.generate_content(model="gemini-3-flash-preview", contents="Explain how AI works in a few words"
)
print(response.text)
如果顺利的话应该已经出来结果了

error1:大概率是环境变量没更新,可以重启一下,不行就再看看有没有设置api错

error2:大概率是你所在地区的网络问题,这个你要到网络支持的地区才行。

成功的情况
5.图片调用
PS:主要你使用的模型额度,还有是否支持图片,有一些模型并非多模态模型,有可能会不支持图片,这里使用 gemini-3-flash-preview 作为示例
code:
import json,os,re
from google import genai
from google.genai import types
from pathlib import Pathimport typing_extensions as typing#https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.cachedContents#Schema
promote_default = ''' #自行根据修改提示词,这里仅作演示
plz explain this img by json:
{'img_name':str,'info': str
}
'''def json_load(input_str: str):try:json_str = re.sub(r'^```(?:json)?\s*', '', input_str.strip())json_str = re.sub(r'\s*```$', '', json_str)json_data = json.loads(json_str)return json_dataexcept Exception as e:print(e)return Nonedef det_example_outputJson(file_path:str,save_path:str, promote:str=promote_default):'''通过指定json结构输出【适用于 gemini2.5+ 】Args:file_path:promote:Returns:'''file_path = file_pathwith open(file_path, 'rb') as f:image_bytes = f.read()client = genai.Client()response = client.models.generate_content(model='gemini-3-flash-preview', #这个自己根据需求设置,也需要看你自己的额度contents=[types.Part.from_bytes(data=image_bytes,mime_type='image/jpeg',),str(promote)],#还支持其他参数的json格式输出,这里只是用promote让他json输出,并非完全格式正确。)try:# response_json = json.loads(response.text)response_json = json_load(response.text)if response_json is None:print(response.text)return# build save pathsave_path: Path = Path(save_path)save_path.mkdir(parents=True, exist_ok=True)save_path = save_path / f'{Path(file_path).stem}.json'#输出的json和你的图片同名,可以根据需要自己修改with open(save_path, 'w', encoding='utf-8') as f:json.dump(response_json, fp=f, indent=4,ensure_ascii=False)# print(json.dumps(response_json, indent=4))print(f'save result to {save_path}')except Exception as e:print(e)print(response.text)returnif __name__ == '__main__':file_path = r'apple.jpg' #自行选择图片,我这里选择了https://pixabay.com/photos/apple-red-red-apple-2788616/的苹果图片save_path = r'path_to_save_dir' #填写文件保存路径【具体到文件夹就行】det_example_outputJson(file_path,save_path)
修改图片地址和保存路径应该就可以输出了【建议jpg图片,其他图片可能会存在兼容性问题】

输出json如上所示
6.尾声
基础入门就大概是这样,感兴趣可以看下限制json的输出和其他调用方式,这里仅作为简单的调用教程。
- json_mode
- json_req_example
- json_字段解析
有多余资金的话可以赞助一下gemin或gpt,毕竟能免费给你调用的厂家不多了,也不要那么暴力调用,过河拆桥。【不过google也是缩次数了#0#,之前好像蛮多次数的给你,只能说用户与厂家之间还是会有各自的盘算吧】

