How to quickly create API Mock Servers using Google Bard and Cloud Run

Johannes H.B.
4 min readJun 1, 2023

--

Introduction

API testing using a mock servers is a valuable tool for API developers. Below are a few benefits of using mock servers for API testing:

  • Speeds up development: Mock servers can be used to simulate real APIs, which allows developers to test their code without having to wait for the real API backends to be ready. This can save a lot of time, especially when developing new features or making changes to existing APIs.
  • Improves quality: Mock servers can be used to test for a variety of scenarios, such as invalid input, unexpected errors, and unexpected load. This can help to improve the quality of APIs by catching bugs early on.
  • Reduces risk: Mock servers can be used to test APIs in isolation, which can help to reduce the risk of breaking other systems when making changes to an API.

In this tutorial, I will show you how to quickly generate API mock servers based on an OpenAPI Specification using Bard and Google Cloud Run.

By combining Bard and Cloud Run, API Developers can quickly and easily generate API mock servers that can be used for testing, development, and collaboration.

Here are the steps involved:

  1. Create an OpenAPI Specification for your API.
  2. Use Bard to generate a mock server code from the OpenAPI Specification.
  3. Deploy the mock server to Cloud Run.
  4. Test your API against the mock server.

We will walk you through each of these steps in more detail in the following sections.

Pre-requisites

  • You have access to Bard
  • You have a Google Cloud project with billing enabled

Step-by-step Tutorial

In this tutorial, I will be using this OpenAPI Spec.

Let’s get started!

  1. First, prepare your OpenAPI specification yaml file and check if it is valid by using an online tool like this one.
  2. Copy your OpenAPI Spec and navigate to Bard
  3. Use the following prompt (or customize it for your own needs) and make sure to replace the placeholder text “PASTE_YOUR_OPENAPI_SPEC_HERE” with your OpenAPI Spec content.
Generate Python Flask code for API a mock server based on 
the following OpenAPI specification: PASTE_YOUR_OPENAPI_SPEC_HERE

4. Bard will respond with Python Flask code. Below is the response in my case:

from flask import Flask, request, jsonify

app = Flask(__name__)

# Define the product data
products = [
{
"id": "1",
"name": "Vintage T-Shirt",
"description": "A classic vintage t-shirt in a variety of colors.",
"picture": "https://example.com/images/vintage-t-shirt.jpg",
"price_usd": {
"currency_code": "USD",
"units": 10,
"nanos": 0
},
"categories": ["vintage", "clothing"]
},
{
"id": "2",
"name": "Gardening Gloves",
"description": "A pair of durable gardening gloves to protect your hands.",
"picture": "https://example.com/images/gardening-gloves.jpg",
"price_usd": {
"currency_code": "USD",
"units": 15,
"nanos": 0
},
"categories": ["gardening", "tools"]
}
]

# Get all products
@app.route("/products", methods=["GET"])
def get_products():
return jsonify({"products": products})

# Get a single product
@app.route("/products/<product_id>", methods=["GET"])
def get_product(product_id):
product = next((product for product in products if product["id"] == product_id), None)
if product is None:
return jsonify({"error": "Product not found"}), 404
return jsonify(product)

if __name__ == "__main__":
app.run(debug=True)

Note: for the same prompt you may get a different code than the one above. Therefore, use it with caution. You may also need to adjust the code as needed and add any missing dependencies.

5. As a next step, we need to prepare our code to be deployed as a Cloud Run Service

  • Navigate to the GCP console
  • Make sure the Cloud Run API is enabled in your project.
  • Open Cloud Shell and create a folder in your main directory
  • Follow the documentation here to prepare your code for deployment to Cloud Run by creating the following files: main.py, requirements.txt, and Dockerfile.
  • Once your code is ready, you can deploy it to Cloud Run using the following gcloud command
gcloud run deploy

You will be prompted to choose a name for your Cloud Run service (mock server) and a GCP region (e.g. us-central1) where your service will be deployed. I recommend to only allow authenticated innovations of Cloud Run service.

Wait a few moments until deployment is complete. On success, the command line displays the service URL.

Testing the API Mock Server

In this example, we will create an Apigee API proxy based on the OpenAPI Specification that we mentioned earlier. We will then use the API Mock Server that we created earlier to test our Apigee API proxy.

  1. Navigate to the Apigee console
  2. Create an API proxy using your OpenAPI Specification, follow the steps described here. Use the URL of the Cloud Run service as a “proxy target endpoint”.
  3. If you have configured your Cloud Run service to only allow authenticated invocations, you will need to create a service account and grant it the “Cloud Run Invoker” role. Once you have done this, you will need to configure your Apigee proxy to use this service account to invoke your mock service. Detailed instructions are explained here
  4. You can use an API client like Postman to make API calls to your API proxy and test its endpoints, see the two examples below:

Example 1: Getting all products

Getting all products

Example 2: Getting a specific product (e.g. id=1)

Getting a specific product

I hope you found this useful. Let me know your feedback in the comments below.

--

--