Back to all courses
There's an API for just about everything these days. Let me show you how to build your own API and make money from it.
I create the best content I possibly can to give away free. My tutorials are generally about web development and include coding languages such as HTML, CSS, Sass, JavaScript, and TypeScript. Subscribe to my YouTube channel for the latest content.
We hear now and then that API has revolutionized the software industry. But what is API, and what does this do?
API stands for Application Programming Interface. The word Application refers to any software with a specific function, whereas, Interface can be understood as a contract of service between two applications. This contract explains how these two interact with each other by means of requests and responses. In simpler terms, consider API as a middle man enabling applications to communicate with each other.
Let’s take a four-step example of two applications to understand how an API works?
Let’s assume YouTube and another random application to help you better understand how an API works as a middle man helping in communication between applications. You can see the YouTube application on the left side, and on the right side is a random one.
YouTube can interact with this application through specific command and request mechanisms.
Let’s say you need to retrieve channel or video information from YouTube. This can be done by sending a simple GET
request to obtain the required information.
Lastly, in step 4, you can even upload a new video from the application to YouTube using an API that bridges the gap between the applications.
Following the example, the whole idea of creating and selling APIs can be classified into four interlinked categories.
The first category, IDEA, is the most challenging part where one needs to think of an API that resolves a real-world problem. It is commonly used by developers who formulate APIs to solve problems, which can benefit other developers facing similar issues so that it can be sold to them. After the IDEA, other categories, i.e., Building, Hosting, and Sellingare perhaps the easiest part.
Given that, let’s develop a top-rated game, Rock, Paper, and Scissors, by building an API. We will use JavaScript and CloudFlare Workers to create this, allowing us to host API free of cost. The following steps will make the task easier:
We can start by installing the CLI tool wrangler, designed for users interested in using Cloudflare Workers. It can be installed via terminal by a simple command:
sh
npm i -g @cloudflare/wrangler
The next step is to log in to your wrangler account through the terminal. For this step, you must register for your CloudFare account free of cost to sign up.
sh
wrangler login
After this, we return to the terminal and run wrangler to generate Rock, Paper, and Scissor.
sh
wrangler generate rock-paper-scissors
Now, go ahead and open the project in your code editor. If you use VS Code, you can run the following command in your terminal to open the project:
sh
code rock-paper-scissors
Once we open up in VS Code, we must write the account_id in a wrangler.toml
file. This account number can be found in your CloudFlare Workers dashboard. To illustrate below, we are using a hypothetical one that will not work if you are not correctly logged in.
toml
name = "rock-paper-scissors"type = "javascript"account id = "94a03164bdf96ae6281fac89feb0c91a"workers_dev = trueroute = " "zone_id = " "
We have a paper that beats rock, scissors which beat paper, and rock which beats scissors, which is just an array of objects. In VS Code, we go to index.js
and start defining our choices along with information about which choice beats which. You can see in the following code snippet that the addEventListener() is attached with an event handler With the background knowledge gained above, we will build an actual API.
js
const CHOICES = [{name: 'paper',beats: 'rock',},{name: 'scissors',beats: 'paper',},{name: 'rock',beats: ' scissors ',},];addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});async function handleRequest(request) {const { searchParams } = new URL(request.url);return new Response('Hello worker!', {headers: { 'content-type': 'text/plain' },});}
The next step we follow is to get a search parameter (searchParams) that will be passed to the API. So when we call the API from our client, we give the API user's choice by passing it in a searchParams
. This searchParams
will be a choice, so that we will request a choice from our searchParams
by the following command:
js
const requestChoice = searchParams.get(choice);
Then next, we need to get our choice from our choices definition. This way, we would know the choice name and what it beats.
js
const userChoice= CHOICES.find((choice) => choice.name === requestChoice);
You can see that we are comparing our choice parameters. We will use this response and return the client results. Instead of returning 'Hello worker!', we will write a getResults() function that passes the user choice and random choice. We will also replace 'text/plain' and return with 'application/jason'. This is how we will do it.
js
async function handleRequest(request) {const { searchParams } = new URL(request.url);const requestChoice = searchParams.get('choice');const userChoice = CHOICES.find(choice => choice.name === requestChoice);return new Response(getResults([userChoice, getRandom()]), {headers: { 'content-type': 'application/json' },});}
Since we are returning JSON, we'll have to stringify this by writing JSON.stringify
to convert it into string. This return will look like this:
js
async function handleRequest(request) {const { searchParams } = new URL(request.url);const requestChoice = searchParams.get('choice');const userChoice = CHOICES.find(choice => choice.name === requestChoice);return new Response(JSON.stringify(getResults([userChoice, getRandom()])), {headers: { 'content-type': 'application/json' },});}
Now we move to the getRandom
function, which will return a random choice from the worker or the AI. We will multiply Math.Random
by CHOICES.length
. This will give us a random number between 0 and 2 as only three choices exist.
js
function getRandom() {const rand = Math.floor(Math.random() * CHOICES.length);}
There are three choices which we have defined earlier. The choice named:
paper beats rocks is choice zero. scissors beats paper is choice one rock beats paper is choice second.
Given that, we will return CHOICES
and then the random index rand
.
js
function getRandom() {const rand = Math.floor(Math.random() * CHOICES.length);return CHOICES[rand];}
Now, we will go back to pass an array of the two choices. The first choice is the user’s choice, and the second is the AI’s. We will write a function getResults
, and here we'll have our choices.
js
function getResults(choices) {const userWins = isWinner(choices);}
We first determine if the user wins by using the function isWinner
where we will passing in our choices. We will now define this simple function. We'll write function isWinner
and give our choices here. We will return the choices index of 0
. We'll see if the first choice beats choices with the index of [1].name
. This will allow us to see if the first choice beats the second choice.
js
function isWinner(choices) {return choices[0].beats === choices[1].name;}
We know that the first choice is the user; hence, we will determine if the user beats the AI. However, we also need to find out if AI beats the user. For this, we'll write:
js
aIWins = isWinner ()
Here, we need to reverse the array because we don't want to affect the array itself. Therefore, we will make a copy of the array using the spread operator since we are using it again later. This will return to us whether the AI wins or not. If we simply write:
js
[...choices].reverse();
The complete function will look like this:
js
function getResults(choices) {const userWins = isWinner(choices);const aiWins = isWinner([...choices].reverse());}
The next step is to get the actual results. We will write a ternary operator, i.e., if the ‘userWins, we're going to return,
You Win, or if the
aiWins, we're going to return
You Lose, or if neither of those is true, we're going to return
Draw`.
Let's bundle this all up into a nice little object. So we're going to create a results object. It is going to have, the user and the user's choice, the AI and AI's choice, and the result. Eventually, we will return the results here.
js
function getResults(choices) {const userWins = isWinner(choices);const aiWins = isWinner([...choices].reverse());const result = userWins ? 'You Win' : aiWins ? 'You Lose' : 'Draw';const results = {user: choices[0],ai: choices[1],result: result,};return results;}
We can test this right now using Wrangler. So we'll open up our terminal
, write $wrangler dev
, and now we have a development server running on a local host.
sh
rock-paper-scissors (master)$ wrangler dev
We can quickly test this by using an application called Paw. We will create a new project, and I'm just going to name this rock, paper, scissors and then create the project.
Here, we're going to add a new request. We'll enter our localhost http://127.0.0.1:8787. We'll need to add a query by adding the parameter of choice, and for value, we can write rock and press send.
We will get a response on the side that is the user chose rock which beats scissors, and the AI picked scissors which beats paper. So that means we won.
We'll get a new response every time we change the value. This time we choose rock, and the AI decides rock which means it’s a draw. If we change this from rock to paper, and the AI picked rock, click send again, and this time we won. We'll get a new response every time we change the value.
Since we built this out using CloudFlare workers, we can easily host our API, even for free, since it's so simple, unless we get a tremendous amount of traffic. To deploy this API, we have to run wrangler publish,
and that's it. So let's test this out from Paw using our new deployed URL. So that's "rock-paper-scissors.codestacker.workers.dev", and we can try different responses and check the results.
The time has arrived to sell our API and start dealing in the cash. To monetize our API, we will sign up for free on RapidAPI Hub to publish our API quickly.
So once we've signed up, go to my APIs, and now we're going to add a new API. Here we have to write a short description; for instance, we can write Play Rock, Paper, Scissors via API. We could select Gaming in the category and then add API.
Write a long description that best suits your game API. Alternatively, you can add a logo and a website, and we've already set the category. We don't have any terms of use. We'll just hit save there.
The second step here is to configure the Base URL. Our URL is following:
https://rock-paper-scissors.codestacker.workers.dev
The third step is to add an Endpoint. it's going to be a REST Endpoint. So we'll click that, and we can name this Choice and give it the description User’s choice. Alternatively, we can add some documentation, which is always good.
Next to this, we have our query parameters. So let's enter that our query parameter is choice. We can see that we have some sample code we could run and test below. We can select a different language. Let's just go to JavaScript fetch.
And this is what that would look like. So notice here that it calls a RapidAPI’s API instead of our actual API. So this way, we can put our API on the marketplace, and users don't see the actual endpoint. Let's go ahead and save to test this endpoint.
We need to test the endpoint, and we can see some responses here. We got our user, which selected rock, and AI picked rock; the result came as a draw. We can see that it is functioning.
We can create an example from this response so that whenever someone is looking at our API in the hub, they can see an example of the response they might get from our API. Let’s go ahead and save that.
We are moving to the plans and pricing now. We have our basic plan of $0 a month, so we can edit this to set it to a monthly subscription or pay per use. We can set the price for the monthly subscription for the basic plan. We'll leave it at zero, but we have to Rate Limit it since it's free.
We can set a Quota limit of a maximum of 100 or 1000 requests per minute and a quota limit monthly; we can select limit type soft. Once they hit this limit, they will begin to be charged per use for overages. We can also set it as a hard limit so that when they hit this, they can no longer use it until the next month.
This package usually serves a developer just to test something out. But if they start using it in production, you want them to upgrade to a paid plan. Let's go ahead and save this, and we can also add a pro plan. For instance, on the pro plan, it can be $10/month, and we will rate limit it. For the pro plan, they'll get 100000 requests/month, and we'll set a soft limit. In the same way, we can add even more plans and ultra-plan or mega-plan.
So now our API is in the hub. We have completed all the requirements, and it is time that we can make it public. We must set API Visibility in DANGER ZONE from Private to Public.
We can cross-check it in the RapidAPI Hub by searching for rock paper scissors, and you will find it there.
Once we open the required API, we can see its details. We can see our newly formulated Rock Paper Scissor API in this case.
So that’s all, folks! We have successfully built a Rock, Paper, Scissor API, deployed it, published it on RapidAPI Hub, and enabled monetization for it to make money. So now go ahead and try it out yourself and make awesome new APIs.