Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Tài liệu này cung cấp tất cả thông tin cơ bản mà bạn cần để bắt đầu sử dụng thư viện.
Tài liệu này đề cập đến các khái niệm về thư viện,
đưa ra ví dụ cho nhiều trường hợp sử dụng,
và cung cấp đường liên kết đến nhiều thông tin khác.
Thiết lập
Bạn cần hoàn tất một số bước thiết lập trước khi có thể sử dụng thư viện này:
Điều quan trọng là bạn phải nắm được những kiến thức cơ bản về cách xử lý việc xác thực và uỷ quyền API.
Tất cả lệnh gọi API phải sử dụng quyền truy cập đơn giản hoặc được uỷ quyền (được định nghĩa bên dưới).
Nhiều phương thức API yêu cầu quyền truy cập được cấp phép, nhưng một số phương thức có thể sử dụng một trong hai phương thức đó.
Một số phương thức API có thể hoạt động theo cách khác,
tuỳ thuộc vào việc bạn sử dụng quyền truy cập đơn giản hay quyền truy cập được uỷ quyền.
Hãy xem tài liệu về phương thức của API để xác định loại quyền truy cập phù hợp.
1. Quyền truy cập API đơn giản (khoá API)
Các lệnh gọi API này không truy cập vào bất kỳ dữ liệu riêng tư nào của người dùng.
Ứng dụng của bạn phải tự xác thực là ứng dụng thuộc về
đối với dự án Google API Console của bạn.
Điều này là cần thiết để đo lường mức sử dụng dự án cho mục đích kế toán.
Khoá API:
Để xác thực ứng dụng của bạn, hãy sử dụng
Khoá API
cho dự án Bảng điều khiển API của bạn.
Mọi lệnh gọi truy cập đơn giản mà ứng dụng của bạn thực hiện đều phải bao gồm khoá này.
2. Quyền truy cập vào API (OAuth 2.0)
Các lệnh gọi API này truy cập vào dữ liệu riêng tư của người dùng.
Trước khi bạn có thể gọi cho họ,
người dùng có quyền truy cập vào dữ liệu cá nhân phải cấp cho ứng dụng của bạn quyền truy cập.
Do đó, đơn đăng ký của bạn phải được xác thực,
người dùng phải cấp quyền truy cập cho ứng dụng của bạn,
và người dùng phải được xác thực để cấp quyền truy cập đó.
Tất cả những điều này được thực hiện nhờ
OAuth 2.0 và các thư viện được viết cho ứng dụng này.
Phạm vi:
Mỗi API xác định một hoặc nhiều phạm vi khai báo một tập hợp thao tác được phép.
Ví dụ: API có thể có phạm vi chỉ đọc và đọc-ghi.
Khi ứng dụng của bạn yêu cầu quyền truy cập vào dữ liệu người dùng,
yêu cầu phải bao gồm một hoặc nhiều phạm vi.
Người dùng cần phê duyệt phạm vi truy cập mà ứng dụng của bạn đang yêu cầu.
Làm mới và truy cập vào mã thông báo:
Khi người dùng cấp quyền truy cập vào ứng dụng của bạn, máy chủ uỷ quyền OAuth 2.0
cung cấp cho ứng dụng của bạn mã làm mới và mã truy cập.
Những mã thông báo này chỉ hợp lệ trong phạm vi được yêu cầu.
Ứng dụng của bạn dùng mã truy cập để cho phép lệnh gọi API.
Mã truy cập sẽ hết hạn, nhưng mã làm mới thì không.
Ứng dụng của bạn có thể dùng mã làm mới để lấy mã truy cập mới.
Mã ứng dụng khách và mật khẩu ứng dụng khách:
Các chuỗi này nhận dạng duy nhất ứng dụng của bạn và dùng để lấy mã thông báo.
Các API này được tạo cho dự án của bạn trên Bảng điều khiển API.
Có 3 loại mã ứng dụng khách,
nên hãy nhớ tìm đúng loại đơn đăng ký của bạn:
Trong phần này, có các ví dụ về việc sử dụng API đơn giản khi chưa được phép.
Để biết thêm thông tin về lệnh gọi uỷ quyền, hãy xem
Trang OAuth 2.0 cho .NET.
Ví dụ về API đơn giản
Ví dụ này sử dụng quyền truy cập API đơn giản cho một ứng dụng dòng lệnh.
Phương thức gọi
Google Discovery API để liệt kê tất cả API của Google.
Ví dụ về chế độ thiết lập
Lấy khoá API đơn giản. Để tìm khoá API cho ứng dụng của bạn, hãy làm như sau:
API này hỗ trợ hai loại thông tin xác thực.
Tạo bất cứ thông tin đăng nhập nào phù hợp với dự án của bạn:
OAuth 2.0: Bất cứ khi nào ứng dụng của bạn yêu cầu người dùng riêng tư
thì ứng dụng phải gửi mã thông báo OAuth 2.0 cùng với yêu cầu. Thông tin
trước tiên sẽ gửi ID ứng dụng khách và có thể là mật khẩu ứng dụng khách để
lấy mã thông báo. Bạn có thể tạo thông tin đăng nhập OAuth 2.0 cho web
ứng dụng, tài khoản dịch vụ hoặc ứng dụng đã cài đặt.
Khoá API:
Một yêu cầu không cung cấp mã thông báo OAuth 2.0 phải gửi API
.
Khoá này giúp xác định dự án của bạn và cấp quyền truy cập vào API, hạn mức và
.
API này hỗ trợ một số loại quy định hạn chế đối với khoá API. Nếu khoá API mà bạn
chưa có, hãy tạo khoá API trong Console bằng cách
nhấp vào Tạo thông tin xác thực
> Khoá API. Bạn có thể hạn chế khoá này trước khi dùng
trong phiên bản phát hành công khai bằng cách nhấp vào Hạn chế khoá rồi chọn một trong
Quy định hạn chế.
usingSystem;usingSystem.Threading.Tasks;usingGoogle.Apis.Discovery.v1;usingGoogle.Apis.Discovery.v1.Data;usingGoogle.Apis.Services;namespaceDiscovery.ListAPIs{///<summary>
///ThisexampleusesthediscoveryAPItolistallAPIsinthediscoveryrepository.///https://developers.google.com/discovery/v1/using.///<summary>
classProgram{[STAThread]staticvoidMain(string[]args){Console.WriteLine("Discovery API Sample");Console.WriteLine("====================");try{newProgram().Run().Wait();}catch(AggregateExceptionex){foreach(vareinex.InnerExceptions){Console.WriteLine("ERROR: "+e.Message);}}Console.WriteLine("Press any key to continue...");Console.ReadKey();}privateasyncTaskRun(){//Createtheservice.varservice=newDiscoveryService(newBaseClientService.Initializer{ApplicationName="Discovery Sample",ApiKey="[YOUR_API_KEY_HERE]",});//Runtherequest.Console.WriteLine("Executing a list request...");varresult=awaitservice.Apis.List().ExecuteAsync();//Displaytheresults.if(result.Items!=null){foreach(DirectoryList.ItemsDataapiinresult.Items){Console.WriteLine(api.Id+" - "+api.Title);}}}}}
Mẹo sử dụng khoá API:
Để sử dụng một dịch vụ cụ thể, bạn phải thêm tệp tham chiếu đến dịch vụ đó.
Ví dụ: nếu bạn muốn sử dụng
API Tasks,
bạn nên cài đặt gói NuGet
Google.Apis.Tasks.v1.
Để tạo một thực thể của một dịch vụ, bạn chỉ cần gọi hàm khởi tạo của dịch vụ đó. Ví dụ:
new TasksService(new BaseClientService.Initializer {...});".
Tất cả các phương thức của một dịch vụ đều nằm trên các tài nguyên riêng lẻ trên chính đối tượng dịch vụ đó.
Dịch vụ Khám phá có một tài nguyên Apis chứa phương thức List.
Khi bạn gọi service.Apis.List(..), một đối tượng yêu cầu nhắm mục tiêu đến phương thức này sẽ được trả về.
Để thực thi một yêu cầu, hãy gọi phương thức Execute() hoặc ExecuteAsyc() trên một yêu cầu.
Đặt khoá API bằng thuộc tính ApiKey trên thực thể BaseClientService.Initializer.
Tìm thông tin về các API
Chiến lược phát hành đĩa đơn
Các API được hỗ trợ
trang liệt kê tất cả API có thể truy cập được bằng thư viện này cũng như các liên kết đến tài liệu.
Bạn cũng có thể sử dụng
Trình khám phá API
để duyệt qua các API, liệt kê các phương thức có sẵn và thậm chí là thử các lệnh gọi API từ trình duyệt của bạn.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\u003cp\u003eThis documentation provides an overview of using the Google API client library for .NET, including setup, authentication, and usage examples.\u003c/p\u003e\n"],["\u003cp\u003eBefore using the library, ensure you have a Google account, a Google API Console project, and install the necessary NuGet package.\u003c/p\u003e\n"],["\u003cp\u003eThe library supports both simple API access using API keys and authorized access with OAuth 2.0 for private user data.\u003c/p\u003e\n"],["\u003cp\u003eSimple API access requires an API key for project usage tracking, while authorized access necessitates OAuth 2.0 for user data access.\u003c/p\u003e\n"],["\u003cp\u003eExamples are provided for basic API usage and guidance on locating further information about supported APIs and the APIs Explorer is included.\u003c/p\u003e\n"]]],[],null,["This document provides all the basic information you need to start using the library.\nIt covers the library concepts,\nshows examples for various use cases,\nand gives links to more information.\n\nSetup\n\n\nThere are a few setup steps you need to complete before you can use this library:\n\n1. If you don't already have a Google account, [sign up](https://www.google.com/accounts).\n2. If you have never created a Google API Console project, read the [Managing Projects page](/console/help/managing-projects) and create a project in the [Google API Console](https://console.cloud.google.com/).\n3. [Install](http://www.nuget.org/packages?q=google.apis&prerelease=true&sortOrder=relevance) the NuGet package you want to work with.\n\nAuthentication and authorization\n\n\nIt is important to understand the basics of how API authentication and authorization are handled.\nAll API calls must use either simple or authorized access (defined below).\nMany API methods require authorized access, but some can use either.\nSome API methods that can use either behave differently,\ndepending on whether you use simple or authorized access.\nSee the API's method documentation to determine the appropriate access type.\n\n1. Simple API access (API keys)\n\n\nThese API calls do not access any private user data.\nYour application must authenticate itself as an application belonging\nto your Google API Console project.\nThis is needed to measure project usage for accounting purposes.\n\n\n**API key** :\nTo authenticate your application, use an\n[API key](/console/help/using-keys)\nfor your API Console project.\nEvery simple access call your application makes must include this key.\n| **Warning**: Keep your API key private. If someone obtains your key, they could use it to consume your quota or incur charges against your API Console project.\n\n\u003cbr /\u003e\n\n2. Authorized API access (OAuth 2.0)\n\n\nThese API calls access private user data.\nBefore you can call them,\nthe user that has access to the private data must grant your application access.\nTherefore, your application must be authenticated,\nthe user must grant access for your application,\nand the user must be authenticated in order to grant that access.\nAll of this is accomplished with\n[OAuth 2.0](/accounts/docs/OAuth2) and libraries written for it.\n\n\n**Scope**:\nEach API defines one or more scopes that declare a set of operations permitted.\nFor example, an API might have read-only and read-write scopes.\nWhen your application requests access to user data,\nthe request must include one or more scopes.\nThe user needs to approve the scope of access your application is requesting.\n\n\n**Refresh and access tokens**:\nWhen a user grants your application access, the OAuth 2.0 authorization server\nprovides your application with refresh and access tokens.\nThese tokens are only valid for the scope requested.\nYour application uses access tokens to authorize API calls.\nAccess tokens expire, but refresh tokens do not.\nYour application can use a refresh token to acquire a new access token.\n| **Warning**: Keep refresh and access tokens private. If someone obtains your tokens, they could use them to access private user data.\n\n\u003cbr /\u003e\n\n\n**Client ID and client secret** :\nThese strings uniquely identify your application and are used to acquire tokens.\nThey are created for your project on the [API Console](https://console.cloud.google.com/).\nThere are three types of client IDs,\nso be sure to get the correct type for your application:\n\n- [Web application](/accounts/docs/OAuth2WebServer) client IDs\n- [Installed application](/accounts/docs/OAuth2InstalledApp) client IDs\n- [Service Account](/accounts/docs/OAuth2ServiceAccount) client IDs\n\n| **Warning**: Keep your client secret private. If someone obtains your client secret, they could use it to consume your quota, incur charges against your Console project, and request access to user data.\n\n\u003cbr /\u003e\n\nExamples\n\n\nIn this section, there are examples of simple API usage without authorization.\nFor more information about authorization calls, see the\n[OAuth 2.0 page for .NET](/api-client-library/dotnet/guide/aaa_oauth).\n\nSimple API example\n\n\nThis example uses simple API access for a command-line application.\nIt calls the\n[Google Discovery API](/discovery) to list all Google APIs.\n\nSetup for example\n\n\n**Get your Simple API key**. To find your application's API key, do the following:\n\n\n1. Open the [Credentials page](https://console.cloud.google.com/apis/credentials) in the API Console.\n2. This API supports two types of credentials. Create whichever credentials are appropriate for your project:\n - **OAuth 2.0:** Whenever your application requests private user\n data, it must send an OAuth 2.0 token along with the request. Your\n application first sends a client ID and, possibly, a client secret to\n obtain a token. You can generate OAuth 2.0 credentials for web\n applications, service accounts, or installed applications.\n\n For more information, see the [OAuth 2.0 documentation](https://developers.google.com/identity/protocols/OAuth2).\n - **API keys:**\n\n A request that does not provide an OAuth 2.0 token must send an API\n key.\n\n The key identifies your project and provides API access, quota, and\n reports.\n\n The API supports several types of restrictions on API keys. If the API key that you\n need doesn't already exist, then create an API key in the Console by\n clicking **[Create credentials](https://console.cloud.google.com/apis/credentials) \\\u003e API key** . You can restrict the key before using it\n in production by clicking **Restrict key** and selecting one of the\n **Restrictions**.\n\nTo keep your API keys secure, follow the [best practices for\nsecurely using API keys](//cloud.google.com/docs/authentication/api-keys).\n\n\u003cbr /\u003e\n\nCode for example \n\n```transact-sql\nusing System;\nusing System.Threading.Tasks;\n\nusing Google.Apis.Discovery.v1;\nusing Google.Apis.Discovery.v1.Data;\nusing Google.Apis.Services;\n\nnamespace Discovery.ListAPIs\n{\n /// \u003csummary\u003e\n /// This example uses the discovery API to list all APIs in the discovery repository.\n /// https://developers.google.com/discovery/v1/using.\n /// \u003csummary\u003e\n class Program\n {\n [STAThread]\n static void Main(string[] args)\n {\n Console.WriteLine(\"Discovery API Sample\");\n Console.WriteLine(\"====================\");\n try\n {\n new Program().Run().Wait();\n }\n catch (AggregateException ex)\n {\n foreach (var e in ex.InnerExceptions)\n {\n Console.WriteLine(\"ERROR: \" + e.Message);\n }\n }\n Console.WriteLine(\"Press any key to continue...\");\n Console.ReadKey();\n }\n\n private async Task Run()\n {\n // Create the service.\n var service = new DiscoveryService(new BaseClientService.Initializer\n {\n ApplicationName = \"Discovery Sample\",\n ApiKey=\"[YOUR_API_KEY_HERE]\",\n });\n\n // Run the request.\n Console.WriteLine(\"Executing a list request...\");\n var result = await service.Apis.List().ExecuteAsync();\n\n // Display the results.\n if (result.Items != null)\n {\n foreach (DirectoryList.ItemsData api in result.Items)\n {\n Console.WriteLine(api.Id + \" - \" + api.Title);\n }\n }\n }\n }\n}\n```\n\n\nTips for using API keys:\n\n- In order to use a specific service, you have to add a reference to it. For example if you want to use the [Tasks API](https://developers.google.com/google-apps/tasks/), you should install its NuGet package [Google.Apis.Tasks.v1](http://www.nuget.org/packages/Google.Apis.Tasks.v1/).\n- To create an instance of a service, just call its constructor. For example: `new TasksService(new BaseClientService.Initializer {...});\"`.\n- All methods of a service are located on individual resources on the service object itself. The Discovery service has an `Apis` resource, which contains a `List` method. When you call `service.Apis.List(..)` a request object targeting this method is returned. \n To execute a request, call the `Execute()` or `ExecuteAsyc()` method on a request.\n- Set the API key using the `ApiKey` property on the `BaseClientService.Initializer` instance.\n\nFinding information about the APIs\n\n\nThe\n[Supported APIs](/api-client-library/dotnet/apis)\npage lists all APIs that can be accessed using this library as well as links to documentation.\n\n\nYou can also use the\n[APIs Explorer](/apis-explorer)\nto browse APIs, list available methods, and even try API calls from your browser."]]