Courseiva
PCDChapter 8 of 15Objective 3.2

Building and Securing APIs

Exam objective 3.2 — Design, build, and secure REST and gRPC APIs on Google Cloud — is the heart of how modern applications talk to each other. If you want to pass the Professional Cloud Developer exam, you need to understand how to create these digital 'waiters' that carry requests between apps and servers, and how to lock them down so only authorised traffic gets through. This chapter makes that clear from the ground up.

12 min read
Intermediate
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Building and Securing APIs

The Restaurant Ordering System Analogy

Have you ever wondered how a takeaway app lets you order a burger without needing to know how the kitchen works?

That app is the client, and the restaurant is a server with an API. When you place an order, you send a request: 'I want a cheeseburger, no onions.' The kitchen receives this, checks if it can fulfil it, prepares the food, and sends back a response: your burger. The menu is the API documentation — it lists what you can order (the available operations), what ingredients are required (parameters), and what you'll get back (response format).

Now, security: the restaurant doesn't just let anyone walk into the kitchen. You place your order through a counter, and the counter staff verify your identity (authentication) and check if you're allowed to order from certain menu items (authorisation — a VIP menu might be for loyalty members only). If you try to order a custom dish not on the menu, the counter says 'invalid request.' If you try to grab someone else's order, the counter rejects you. If the kitchen can't fulfil your order, you get an error status — like a '404 Not Found' if the item is off the menu.

In this analogy, the restaurant's ordering protocol (REST) ensures every interaction follows the same rules: each request is stand-alone (stateless), the menu is the single source of truth (uniform interface), and orders never depend on prior orders. If the restaurant used a different system (gRPC), it'd be like a waiter who speaks a coded language to the kitchen for faster, more efficient communication with strict type-checking on each ingredient. Building and securing APIs is essentially designing this restaurant's counter and security measures so any customer (app) can order reliably, safely, and without chaos.

How It Actually Works

An API, short for Application Programming Interface, is a set of rules that allows one piece of software to talk to another. Think of it as a messenger that takes a request from your app, tells a server what to do, and brings back the result. Without APIs, each app would need to be custom-built to connect to every other system — that would be a nightmare. APIs standardise that conversation so developers can focus on building features, not wiring up connections.

On Google Cloud, you typically build two kinds of APIs: REST and gRPC. REST (Representational State Transfer) is the most common style. It uses standard HTTP methods like GET (fetch data), POST (create new data), PUT (update data), and DELETE (remove data). Each request is independent — this is called being stateless, meaning the server doesn't remember past requests. Every request carries all the information needed to process it. REST APIs usually return data in JSON (JavaScript Object Notation) format, which is easy for humans and machines to read.

gRPC (gRPC Remote Procedure Call) is a newer, faster alternative developed by Google. Instead of JSON, it uses Protocol Buffers (protobufs) — a compact binary format that makes data transfer much faster and smaller. It also uses HTTP/2, which allows multiple messages to be sent over a single connection. gRPC is great for internal microservices (small, independent services that together form an application) because it's efficient and supports streaming (sending data as a continuous flow, not just a single response). However, it's harder to debug than REST because the data isn't human-readable.

Now, security is non-negotiable. You must protect APIs from unauthorised access. The main tools on Google Cloud are:

Authentication: verifying who the caller is. This is often done with API keys (simple identifier tokens) or OAuth 2.0 (a more secure protocol that issues access tokens after a user logs in).

Authorisation: checking what the caller is allowed to do. This uses Identity and Access Management (IAM) roles and permissions.

Transport security: encrypting data in transit using TLS (Transport Layer Security), which ensures no one can eavesdrop on the conversation.

You also need to handle errors gracefully. Common HTTP status codes include 200 OK (success), 201 Created (resource made), 400 Bad Request (client error), 401 Unauthorised (no or bad credentials), 403 Forbidden (not allowed), and 500 Internal Server Error (server problem).

Why does this matter for the PCD exam? You'll be asked to design APIs that follow RESTful principles (like resource naming with nouns, not verbs — e.g., /users not /getUsers). You'll need to know how to secure them using Cloud Endpoints, Apigee (a full API management platform), or Cloud Load Balancing with IAM. You'll also see questions about choosing between REST and gRPC based on performance needs, and about implementing pagination (splitting large result sets into pages) and versioning (e.g., /v1/users) to avoid breaking existing clients.

In practice, building an API on Google Cloud involves defining your resources, choosing your protocol, setting up authentication with Firebase or OAuth, and deploying behind Cloud Endpoints or a load balancer. You then monitor it with Cloud Logging and Cloud Monitoring to catch errors and performance issues. The exam expects you to know these steps cold, including the exact services and their purposes.

This diagram shows the data flow for a secured API request: the client sends an HTTPS request with an OAuth token to Cloud Endpoints, which verifies the token, checks IAM permissions, then forwards authorised requests to a backend service that may call internal microservices via REST or gRPC.

Walk-Through

1

Define the API resources and actions

Identify the core objects your API will manage (e.g., users, products, orders) and map each to a URI. Decide which HTTP methods correspond to which actions: GET for reading, POST for creating, PUT for full updates, PATCH for partial updates, DELETE for removal. This step sets the structure and ensures RESTful naming conventions.

2

Choose the protocol: REST or gRPC

Decide whether to use REST with JSON or gRPC with Protocol Buffers. REST is simpler and more browser-friendly; gRPC is faster and supports streaming. For public client-facing APIs, choose REST. For internal service-to-service communication with high throughput needs, choose gRPC. This decision affects tooling, data formats, and deployment options.

3

Design the authentication and authorisation scheme

Determine how users or services will prove their identity (authentication) and what they're allowed to do (authorisation). For user-facing apps, use OAuth 2.0 with tokens. For service-to-service, use service accounts. Configure IAM roles to grant or deny access to specific API endpoints. This step is critical for security and is heavily tested on the exam.

4

Implement the API with input validation and error handling

Write the backend code that processes requests, validates input (e.g., check that required fields exist, data types are correct), and returns appropriate HTTP status codes and error messages. Use standard codes: 200 for success, 400 for bad request, 401/403 for auth failures, 500 for server errors. Consistent error handling makes your API easier to debug.

5

Deploy and secure with API gateway or load balancer

Deploy your backend service (e.g., on Cloud Run, App Engine, or Compute Engine) behind an API gateway like Cloud Endpoints or Apigee. The gateway handles SSL termination (HTTPS), token verification, rate limiting, logging, and monitoring. This step ensures all traffic is encrypted and that your API is protected from abuse and attacks.

6

Test, document, and version the API

Write automated tests for each endpoint using tools like Postman or pytest. Generate OpenAPI documentation so other developers know how to call your API. Implement versioning (e.g., /v1/ vs /v2/ URIs) from day one so you can make breaking changes later without disrupting existing users. Deploy the documentation to a developer portal.

7

Monitor and iterate

Set up Cloud Monitoring and Cloud Logging dashboards to track request counts, error rates, latency, and usage patterns. Use alerts to notify you of problems like 5xx errors spikes or slow response times. Based on data, optimise endpoints or add caching. Continuous improvement keeps your API stable and performant.

What This Looks Like on the Job

Imagine you work at a retail company building a mobile app for customers to browse products, place orders, and track delivery. As the cloud developer, you're tasked with building the backend API that the app will talk to. Here's what you actually do.

First, you design the REST API endpoints. You decide that all product-related requests go to /v1/products, and order requests to /v1/orders. You use GET for fetching data (e.g., GET /v1/products?category=shoes), POST for creating (e.g., POST /v1/orders with order details in the request body), and PUT for updating (e.g., PUT /v1/orders/123 to change a shipping address). Each endpoint returns JSON.

Next, you secure it. You set up Google Cloud Endpoints to manage your API. You configure authentication using Firebase Authentication so that users sign in with their email or Google account, and the app receives an ID token. Every API request must include this token in the Authorization header. On the backend, Cloud Endpoints verifies the token and extracts the user's identity. Then you apply authorisation using IAM: you create a custom role called 'order_creator' that grants permission to call POST /v1/orders, and assign it to authenticated users. For sensitive admin endpoints (like deleting products), you require a stronger role.

You also handle errors consistently. If a user tries to fetch an order that doesn't belong to them, you return 403 Forbidden with a clear message. If the request body is malformed, you return 400 Bad Request. You add pagination to the products endpoint using page tokens (the API returns a next_page_token field) so the app can request the next batch of 20 products without overwhelming the server.

For internal services — say, the inventory management system that needs real-time stock updates — you choose gRPC instead of REST. You define the service in a .proto file using Protocol Buffers, specifying methods like GetStockLevel(product_id) and SubscribeToStockUpdates(product_id) (a gRPC streaming call). You deploy this as a Cloud Run service with IAM authentication between services, using service accounts (special accounts for machines) rather than user tokens.

Finally, you monitor everything. You set up Cloud Logging to capture all API requests and errors, and Cloud Monitoring to alert you if response times exceed 500ms or if error rates spike above 1%. You test the API with tools like curl or Postman, and deploy the REST API behind Cloud Endpoints with automatic SSL/TLS encryption.

In a real team, you'd also version your API from day one (v1) so that when you later release v2 with breaking changes, existing app users aren't affected. You'd document the API using OpenAPI specs (a standard for describing APIs) so frontend developers know exactly what to send and receive. This whole process — design, secure, deploy, document, monitor — is what the PCD exam expects you to know how to do.

How PCD Actually Tests This

The PCD exam tests Building and Securing APIs from several angles, and you need to be specific. First, expect scenario-based multiple-choice questions where you must pick the correct way to design an endpoint. A common trap: they'll give you a URI like /getUserDetails?id=5 and ask if this is RESTful. The correct answer is 'no' because RESTful URIs should use nouns, not verbs — the correct form is /users/5 with GET method. They love testing this distinction.

Authentication vs. authorisation is another favourite. You'll see a scenario where a user can make a request but gets a 403 error. The question: 'Was this an authentication or authorisation failure?' The answer is authorisation — the user is identified (authentication worked) but not permitted (authorisation failed). A 401 error means authentication failed (no valid credentials). Remember these status codes perfectly.

You'll also face questions about choosing between REST and gRPC. The exam will give you performance requirements like 'low latency, high throughput, streaming needed' — the answer is gRPC with Protocol Buffers. If they say 'public-facing, needs to be easily debugged, supports many client types' — the answer is REST with JSON.

Security topics are huge. Expect questions on:

Using API keys vs. OAuth 2.0. API keys are simpler but less secure; OAuth 2.0 is preferred for user-facing apps.

IAM roles for API access. You'll need to know that Cloud Endpoints can use service accounts to call other Google Cloud services.

Protecting against common attacks like SQL injection (they won't test SQL injection deeply, but you should know to use parameterised queries) and DDoS (use Cloud Armor for web application firewall).

A trap they often set: asking about versioning. You'll see 'We want to update our API without breaking existing clients. What should we do?' The correct answer is 'Use URI versioning (e.g., /v1/users, /v2/users)', not a query parameter like /users?version=2.

Finally, they test pagination. A typical question: 'An API returns 1000 items but the client only needs 50 at a time. How should you implement this?' Correct: use page tokens or offset/limit parameters, and include the next page token in the response. They'll try to trick you into saying 'return all items at once' — don't fall for it.

Key definitions to memorise:

REST: stateless, cacheable, uniform interface, layered system.

gRPC: uses HTTP/2, Protocol Buffers, supports streaming, bidirectional communication.

OAuth 2.0: delegated authorisation framework using tokens.

Cloud Endpoints: managed API gateway for authentication, monitoring, and routing.

Apigee: full API management platform with analytics, monetisation, and developer portal.

Study the Google Cloud documentation on Cloud Endpoints and gRPC specifically — that's where exam questions pull from. Practise with sample questions to get comfortable with the style.

Key Takeaways

REST APIs use standard HTTP methods (GET, POST, PUT, DELETE) and resource-based URIs with nouns, not verbs.

gRPC uses Protocol Buffers and HTTP/2 for faster, more efficient communication between internal microservices.

Authentication (who you are) uses tokens like OAuth 2.0; authorisation (what you can do) uses IAM roles and permissions.

HTTPS encrypts data in transit but does not replace the need for input validation, authentication, or access controls.

API versioning via URI paths (e.g., /v1/users) is essential to avoid breaking existing clients when you change your API.

Pagination ensures you don't overwhelm clients or servers by returning large datasets in manageable chunks with page tokens.

A 401 status means no valid credentials provided; a 403 status means credentials present but insufficient permissions.

Cloud Endpoints on Google Cloud provides authentication, monitoring, and request validation for your APIs without extra code.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

REST

Uses HTTP/1.1 typically; requests are text-based JSON

Public-facing APIs; easy to debug with browser tools

Limited to request-response messaging; no native streaming

gRPC

Uses HTTP/2; binary Protocol Buffers for smaller payloads

Ideal for internal microservices; high performance

Supports bidirectional streaming and real-time data flow

OAuth 2.0

Issues access tokens after user login; supports scopes

More secure because tokens are time-limited and revocable

Standard for user-facing applications and delegated access

API Keys

Simple string identifier; no user context

Less secure; often exposed in client-side code

Suitable for project-level identification, not user authentication

HTTP 401 Unauthorised

No valid authentication credentials were provided

Client can retry with correct credentials

Server does not know the identity of the requester

HTTP 403 Forbidden

Authentication succeeded but access is denied

Client should not retry with same credentials

Server knows identity but lacks permissions

Cloud Endpoints

Lightweight, fully managed by Google Cloud

Tightly integrated with Cloud Run, App Engine, GKE

Simple authentication, logging, and quota management

Apigee

Full API management platform with analytics and monetisation

Rich policy engine for security, traffic management, and transformation

Includes developer portal and marketplace capabilities

Watch Out for These

Mistake

REST APIs must always return JSON and nothing else.

Correct

REST APIs can return any format — XML, plain text, YAML, or even binary data. JSON is the most common because it's lightweight and easy to parse, but it's not a requirement of the REST architectural style.

Many tutorials exclusively use JSON examples, so beginners assume it's mandatory. The REST architectural constraints don't specify a data format.

Mistake

Using HTTPS automatically secures the API from all threats.

Correct

HTTPS (HTTP over TLS) only encrypts data in transit between client and server. It does not prevent issues like broken authentication, injection attacks, or insufficient authorisation. You still need proper authentication, validation, and access controls.

People conflate 'encryption' with 'security.' Encryption is one layer, not a silver bullet. It's like locking the car door but leaving the windows open.

Mistake

gRPC is always faster than REST, so you should use it for everything.

Correct

gRPC is faster for internal microservice communication due to binary serialisation and HTTP/2, but it's not always better. REST is easier to debug, works with any HTTP client, and is more compatible with browsers and firewalls. For public-facing APIs that need broad adoption, REST is usually the better choice.

Developers see benchmark numbers showing gRPC speed and assume it's universally superior. They overlook the trade-offs in complexity and tooling support.

Mistake

API keys are a secure form of authentication for user-facing applications.

Correct

API keys are simple identifiers that can be easily leaked if embedded in client-side code (like mobile apps or browser JavaScript). They are not suitable for user authentication because they don't represent a specific user — they identify the project. Use OAuth 2.0 tokens for user-level authentication.

Beginners see API keys as 'secret codes' and treat them like passwords. But because they are often visible in client code, they are inherently less secure. It's a common rookie mistake in real-world projects.

Mistake

A 401 Unauthorised status code means the user is not allowed to access the resource.

Correct

401 Unauthorised means the request lacks valid authentication credentials — the user is not identified. If the user is identified but not permitted to access the resource, the correct status code is 403 Forbidden. Mixing these two is a frequent source of bugs.

The phrase 'unauthorised' sounds like 'not authorised', so beginners use it for permission failures. HTTP status codes have specific meanings that differ from everyday language.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the key difference between REST and gRPC APIs?

REST uses HTTP methods, JSON, and readable URIs; gRPC uses Protocol Buffers (binary format) and HTTP/2 for faster, smaller messages. REST is easier to debug and works with browsers; gRPC is more efficient for internal microservices and supports streaming.

Do I need to use HTTPS for my API on Google Cloud?

Yes, absolutely. HTTPS encrypts data in transit, protecting against eavesdropping and tampering. Google Cloud services like Cloud Endpoints and Load Balancing automatically provide SSL certificates when you configure HTTPS.

What is a service account and why is it used for APIs?

A service account is a special Google account for machines, not humans. It has its own email address and private key. You use it to authenticate your backend services when they call other Google Cloud APIs, because it allows secure, automated access without storing user passwords.

How do I handle multiple clients wanting different versions of my API?

Use URI versioning: define your base path as /v1/ for the first version and /v2/ for the next. Existing clients continue using the old version without breaking. Avoid query parameter versioning as it's less standard and harder to cache.

What does stateless mean in REST APIs?

Stateless means each request from a client contains all the information the server needs to process it — the server does not store any client context between requests. This makes APIs simpler to scale because any server can handle any request independently.

Why would I choose Cloud Endpoints over Apigee for my API?

Cloud Endpoints is a lightweight, managed API gateway tightly integrated with Google Cloud services, good for simple authentication and monitoring. Apigee is a full-featured API management platform with analytics, developer portal, monetisation, and advanced security policies — better for large-scale enterprise APIs.

Terms Worth Knowing

Keep going

You've finished Building and Securing APIs. Continue through the PCD study guide to build a complete picture of the exam.

Done with this chapter?