Create an API Key

Sprawdź postępy

/ 40

Make an Entity Analysis Request and save the result

Sprawdź postępy

/ 60

Ten moduł może zawierać narzędzia AI, które ułatwią Ci naukę.
Te treści nie są jeszcze zoptymalizowane pod kątem urządzeń mobilnych.
Dla maksymalnej wygody odwiedź nas na komputerze, korzystając z linku przesłanego e-mailem.

GSP038

Google Cloud self-paced labs

Overview

The Cloud Natural Language API lets you extract entities from text, perform sentiment and syntactic analysis, and classify text into categories.

In this lab, you learn how to use the Cloud Natural Language API to analyze entities, sentiment, and syntax.

What you'll learn

In this lab, you learn how to perform the following tasks:

  • Create a Cloud Natural Language API request and call the API with curl.
  • Extract entities and run sentiment analysis on text with the Cloud Natural Language API.
  • Perform linguistic analysis on text with the Cloud Natural Language API.
  • Create a Cloud Natural Language API request in a different language.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method. On the right is the Lab setup and access panel with the following:

    • The Open Google Cloud console button
    • The temporary credentials (username and password) that you must use for this lab
    • Other information, if needed, to step through this lab

    Note that the lab timer is located near the top of the page, showing the remaining time.

  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab setup and access panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab setup and access panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field. Navigation menu icon and Search field

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

  2. Click through the following windows:

    • Continue through the Cloud Shell information window.
    • Authorize Cloud Shell to use your credentials to make Google Cloud API calls.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Create an API key

Because you use curl to send a request to the Cloud Natural Language API, you must generate an API key to pass in your request URL.

  1. To create an API key, in the Google Cloud console, on the Navigation menu, click APIs & Services > Credentials.

  2. Click Create credentials, and then select API key.

  3. In the Create API key side panel, under APIs that can be accessed using this key, click the Select APIs drop-down menu.

  4. Search for Cloud Natural Language API, and then select the Cloud Natural Language API checkbox.

  5. Click OK.

  6. Click Create.

  7. Copy the generated API key, and then click Close.

  8. In Cloud Shell, run the following command to save the API key to an environment variable, replacing <YOUR_API_KEY> with the key that you copied:

export API_KEY=

Click Check my progress to verify the objective.

Create an API Key

Task 2. Make an entity analysis request

The first Cloud Natural Language API method you use is analyzeEntities. With this method, the API can extract entities (such as people, places, and events) from text. To test the API's entity analysis, use the following sentence:

Joanne Rowling, who writes under the pen names J. K. Rowling and Robert Galbraith, is a British novelist and screenwriter who wrote the Harry Potter fantasy series.

You build your request to the Cloud Natural Language API in the request.json file.

  1. In Cloud Shell, run the following command to create and open request.json in the nano text editor:
nano request.json
  1. Paste the following JSON code into request.json:
{ "document":{ "type":"PLAIN_TEXT", "content":"Joanne Rowling, who writes under the pen names J. K. Rowling and Robert Galbraith, is a British novelist and screenwriter who wrote the Harry Potter fantasy series." }, "encodingType":"UTF8" }
  1. Press CTRL+X to exit nano, press Y to save the file, and then press ENTER to confirm.

In the request, you tell the Cloud Natural Language API about the text that you send. Supported type values are PLAIN_TEXT or HTML. In content, you pass the text to send to the Cloud Natural Language API for analysis.

The Cloud Natural Language API also supports sending files stored in Cloud Storage for text processing. To send a file from Cloud Storage, you replace content with gcsContentUri and specify the text file's URI in Cloud Storage.

The encodingType parameter tells the API which type of text encoding to use when processing your text. The API uses this parameter to calculate where specific entities appear in your text.

Task 3. Call the Natural Language API

  1. Run the following curl command to pass your request body and the API key environment variable that you saved earlier to the Cloud Natural Language API:
curl "https://language.googleapis.com/v1/documents:analyzeEntities?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json > result.json
  1. To check the response, run the following command:
cat result.json

The beginning of your response should look like this:

"content": "Joanne Rowling", "beginOffset": 0 }, "type": "PROPER" }, { "text": { "content": "Rowling", "beginOffset": 53 }, "type": "PROPER" }, { "text": { "content": "novelist", "beginOffset": 96 }, "type": "COMMON" }, { "text": { "content": "Robert Galbraith", "beginOffset": 65 }, "type": "PROPER" } ] }, ... ] }

For each entity in the response, you get the entity type, the associated Wikipedia URL if there is one, the salience, and the indices of where this entity appeared in the text. Salience is a number in the [0,1] range that refers to the centrality of the entity to the text as a whole.

The Cloud Natural Language API can also recognize the same entity mentioned in different ways. In the mentions list in the response, the API can tell that "Joanne Rowling", "Rowling", "novelist", and "Robert Galbraith" all point to the same entity.

  1. Run the following command to upload the result.json file to your Cloud Storage bucket:
gcloud storage cp result.json gs://{{{project_0.project_id | PROJECT_ID}}}-nlp/

Click Check my progress to verify the objective.

Make an Entity Analysis Request and save the result

Task 4. Perform sentiment analysis with the Natural Language API

In addition to extracting entities, the Cloud Natural Language API lets you perform sentiment analysis on a block of text. This JSON request includes the same parameters as the previous request, except that the text expresses a stronger sentiment.

  1. Open request.json in nano and replace its contents with the following JSON code (you can also replace the content value with your own text):
{ "document":{ "type":"PLAIN_TEXT", "content":"Harry Potter is the best book. I think everyone should read it." }, "encodingType": "UTF8" }
  1. Press CTRL+X to exit nano, press Y to save the file, and then press ENTER to confirm.

  2. Run the following curl command to send the request to the API's analyzeSentiment endpoint:

curl "https://language.googleapis.com/v1/documents:analyzeSentiment?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json

Your response should look like this:

{ "documentSentiment": { "magnitude": 1.9, "score": 0.9 }, "language": "en", "sentences": [ { "text": { "content": "Harry Potter is the best book.", "beginOffset": 0 }, "sentiment": { "magnitude": 0.9, "score": 0.9 } }, { "text": { "content": "I think everyone should read it.", "beginOffset": 31 }, "sentiment": { "magnitude": 0.9, "score": 0.9 } } ] } Note: Your scores might differ slightly from the example output.

Notice that you get two types of sentiment values: sentiment for the document as a whole, and sentiment divided by sentence. The sentiment method returns two values:

  • score: A number from -1.0 to 1.0 that indicates how positive or negative the statement is.
  • magnitude: A number ranging from 0 to infinity that represents the weight of sentiment expressed in the statement, regardless of whether it is positive or negative.

Longer blocks of text with heavily weighted statements have higher magnitude values. The score for the first sentence is positive (0.7), whereas the score for the second sentence is neutral (0.1).

Task 5. Analyze entity sentiment

In addition to providing sentiment details on the entire text document, the Cloud Natural Language API can also analyze sentiment by the entities in the text. Use this sentence as an example:

I liked the sushi but the service was terrible.

In this case, getting a sentiment score for the entire sentence as you did earlier might not be as useful. If this were a restaurant review and there were hundreds of reviews for the same restaurant, you'd want to know which specific things people liked and didn't like in their reviews. Fortunately, the Cloud Natural Language API has a method called analyzeEntitySentiment that lets you get the sentiment for each entity in the text. Test how this method works in the following steps.

  1. Open request.json in nano and replace its contents with the following JSON code:
{ "document":{ "type":"PLAIN_TEXT", "content":"I liked the sushi but the service was terrible." }, "encodingType": "UTF8" }
  1. Press CTRL+X to exit nano, press Y to save the file, and then press ENTER to confirm.

  2. Run the following curl command to call the analyzeEntitySentiment endpoint:

curl "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json

In the response, you get back two entity objects: one for "sushi" and one for "service". Here's the full JSON response:

{ "entities": [ { "name": "sushi", "type": "CONSUMER_GOOD", "metadata": {}, "salience": 0.51064336, "mentions": [ { "text": { "content": "sushi", "beginOffset": 12 }, "type": "COMMON", "sentiment": { "magnitude": 0, "score": 0 } } ], "sentiment": { "magnitude": 0, "score": 0 } }, { "name": "service", "type": "OTHER", "metadata": {}, "salience": 0.48935664, "mentions": [ { "text": { "content": "service", "beginOffset": 26 }, "type": "COMMON", "sentiment": { "magnitude": 0.7, "score": -0.7 } } ], "sentiment": { "magnitude": 0.7, "score": -0.7 } } ], "language": "en" }

The response returns a neutral score of 0 for "sushi", whereas "service" receives a score of -0.7. Notice that the response also returns two sentiment objects for each entity. If the text mentions either term more than once, the API returns a separate sentiment score and magnitude for each mention, along with an aggregate sentiment for the entity.

Note: Your scores might differ slightly from the example output.

Task 6. Analyze syntax and parts of speech

Use syntactic analysis, another of the Cloud Natural Language API's methods, to explore the linguistic details of the text. The analyzeSyntax method extracts linguistic information, breaking up the given text into a series of sentences and tokens (generally, word boundaries) to provide further analysis on those tokens. For each word in the text, the API tells you the word's part of speech (noun, verb, adjective, etc.) and how it relates to other words in the sentence (for example, whether it is the root verb or a modifier).

Test this method with a simple sentence. This JSON request is similar to the previous requests, with the addition of a features key. This tells the API to perform syntax annotation.

  1. Open request.json in nano and replace its contents with the following JSON code:
{ "document":{ "type":"PLAIN_TEXT", "content": "Joanne Rowling is a British novelist, screenwriter and film producer." }, "encodingType": "UTF8" }
  1. Press CTRL+X to exit nano, press Y to save the file, and then press ENTER to confirm.

  2. Run the following curl command to call the API's analyzeSyntax method:

curl "https://language.googleapis.com/v1/documents:analyzeSyntax?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json

The response returns an object similar to the following for each token in the sentence:

{ "text": { "content": "is", "beginOffset": 15 }, "partOfSpeech": { "tag": "VERB", "aspect": "ASPECT_UNKNOWN", "case": "CASE_UNKNOWN", "form": "FORM_UNKNOWN", "gender": "GENDER_UNKNOWN", "mood": "INDICATIVE", "number": "SINGULAR", "person": "THIRD", "proper": "PROPER_UNKNOWN", "reciprocity": "RECIPROCITY_UNKNOWN", "tense": "PRESENT", "voice": "VOICE_UNKNOWN" }, "dependencyEdge": { "headTokenIndex": 2, "label": "ROOT" }, "lemma": "be" },

Review the key fields in the response:

  • partOfSpeech tells you that "Joanne" is a noun.
  • dependencyEdge includes data that you can use to create a dependency parse tree of the text. Essentially, this is a diagram showing how words in a sentence relate to each other. A dependency parse tree for the preceding sentence looks like this:

Dependency parse tree

Note: You can create your own dependency parse trees in the browser with the Natural Language demo available in the Cloud Natural Language AI documentation.
  • headTokenIndex is the index of the token that has an arc pointing at "Joanne". Think of each token in the sentence as a word in an array.
  • A headTokenIndex of 1 for "Joanne" refers to the word "Rowling", which it connects to in the tree. The label NN (short for noun compound modifier) describes the word's role in the sentence. "Joanne" modifies "Rowling", the subject of the sentence.
  • lemma is the canonical form of the word. For example, the words run, runs, ran, and running all have a lemma of run. The lemma value is useful for tracking occurrences of a word in a large piece of text over time.

Task 7. Perform multilingual natural language processing

The Cloud Natural Language API also supports languages other than English (for the full list, see the Language Support Guide).

  1. Open request.json in nano and replace its contents with the following JSON code containing a sentence in Japanese:
{ "document":{ "type":"PLAIN_TEXT", "content":"日本のグーグルのオフィスは、東京の六本木ヒルズにあります" } }
  1. Press CTRL+X to exit nano, press Y to save the file, and then press ENTER to confirm.

Notice that you didn't specify the language of the text—the API automatically detects it!

  1. Run the following curl command to send the request to the analyzeEntities endpoint:
curl "https://language.googleapis.com/v1/documents:analyzeEntities?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json

The command returns the following response:

{ "entities": [ { "name": "日本", "type": "LOCATION", "metadata": { "mid": "/m/03_3d", "wikipedia_url": "https://en.wikipedia.org/wiki/Japan" }, "salience": 0.23854347, "mentions": [ { "text": { "content": "日本", "beginOffset": 0 }, "type": "PROPER" } ] }, { "name": "グーグル", "type": "ORGANIZATION", "metadata": { "mid": "/m/045c7b", "wikipedia_url": "https://en.wikipedia.org/wiki/Google" }, "salience": 0.21155767, "mentions": [ { "text": { "content": "グーグル", "beginOffset": 9 }, "type": "PROPER" } ] }, ... ] "language": "ja" }

The Wikipedia URLs even point to the corresponding Wikipedia pages!

Congratulations!

You've learned how to perform text analysis with the Cloud Natural Language API by extracting entities, analyzing sentiment, and doing syntax annotation. In this lab, you created a Cloud Natural Language API request and called the API with curl, extracted entities and ran sentiment analysis on text with the Cloud Natural Language API, performed linguistic analysis on text, and created a Cloud Natural Language API request in a different language.

Next steps / Learn more

Learn more from the Cloud Natural Language API tutorials in the documentation.

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated November 18, 2026

Lab Last Tested November 8, 2026

Copyright 2026 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Zanim zaczniesz

  1. Moduły tworzą projekt Google Cloud i zasoby na określony czas.
  2. Moduły mają ograniczenie czasowe i nie mają funkcji wstrzymywania. Jeśli zakończysz moduł, musisz go zacząć od początku.
  3. Aby rozpocząć, w lewym górnym rogu ekranu kliknij Rozpocznij moduł.

Użyj przeglądania prywatnego

  1. Skopiuj podaną nazwę użytkownika i hasło do modułu.
  2. Kliknij Otwórz konsolę w trybie prywatnym.

Zaloguj się w konsoli

  1. Zaloguj się z użyciem danych logowania do modułu. Użycie innych danych logowania może spowodować błędy lub naliczanie opłat.
  2. Zaakceptuj warunki i pomiń stronę zasobów przywracania.
  3. Nie klikaj Zakończ moduł, chyba że właśnie został przez Ciebie zakończony lub chcesz go uruchomić ponownie, ponieważ spowoduje to usunięcie wyników i projektu.

Ta treść jest obecnie niedostępna

Kiedy dostępność się zmieni, możemy wysłać Ci e-maila z powiadomieniem

Świetnie

Kiedy dostępność się zmieni, możemy skontaktować się z Tobą e-mailem

Jeden moduł, a potem drugi

Potwierdź, aby zakończyć wszystkie istniejące moduły i rozpocząć ten

Aby uruchomić moduł, użyj przeglądania prywatnego

Najlepszym sposobem na uruchomienie tego laboratorium jest użycie okna incognito lub przeglądania prywatnego. Dzięki temu unikniesz konfliktu między swoim kontem osobistym a kontem do nauki, co mogłoby spowodować naliczanie dodatkowych opłat na koncie osobistym.