Back to all courses
In this API Crash Course, I'll teach you what an API is, how to use multiple APIs in your application, and even how to build and sell your own API to make money!
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.
There's this exciting thing called API, and if you're not sure what it is, you'll learn how to build one, host it, and sell it by the end of this guide.
Additionally, you will discover in-depth information about what an API is, how to use and manage several APIs simultaneously, how to create an API, and even how to sell an API.
Let's get started right away by defining API. API stands for an application programming interface. It provides a channel for interaction between two or more computer programs. It is a software interface that provides a service to other programs. The best way to explain it is with an example.
To understand how an API works, consider a four-step example of two applications.
Assume YouTube and another random application to better understand how an API functions as a middleman facilitating communication between applications. On the left side, you can see the YouTube application, and on the right, you can see a random one.
YouTube can interact with this application via specific command and request mechanisms.
Assume you need to retrieve information about a YouTube channel or video. This is accomplished by sending a simple 'GET' request to obtain the necessary information.
Last but not least, leveraging an API that connects the applications, you may upload a fresh video from the application to YouTube
Imagine that you have an application that uses multiple APIs from different platforms. Each API has a unique key and access control mechanism.
Would you believe me if I told you there is a platform where you can manage all of your APIs in a single place? To demonstrate how simple RapidAPI is to use, we're going to design an app that incorporates multiple APIs.
Before we begin, let's take a look at the RapidAPI Hub website. It's the next-generation API platform where you can discover, connect to, and manage thousands of APIs.
It is the biggest API Hub in the world and contains all the APIs you require in one location. Using a single account API key and SDK, you can use it to access as many APIs as your application needs.
It is the biggest API Hub in the world and contains all the APIs you require in one location. Using a single account API key and SDK, you can use it to access as many APIs as your application needs.
You can build applications using a number of APIs. This platform offers some of the best APIs, including those from Twilio, Microsoft, Google, SendGrid, TeleSign, and many others.
The dashboard also allows you to manage and analyze the performance of your APIs. It will offer brief explanations of how to manage and visualize different responses and requests made to various APIs.
Let's take a look around the RapidAPI Hub website, where we can find various API categories, including recommended and popular APIs. You can open the website through this link RapidAPI Hub
In the top search bar, we can look for any required API. Let's look for "geolocation API." Let’s go with IP Geo Location API.
When you visit its API page, the documentation interface appears. This will provide us with a testing environment for our API.
You can tell that it is a freemium API. The Pricing option allows us to review the specifics. We'll make use of the Basic plan, which is free and ideal for development because it allows for 500 requests per day. When you're ready for production, you can switch to premium plans.
For more processing, let's return to Endpoints. In order to view the results, we can select the Test Endpoint button. The user's latitude and longitude are displayed, along with their IP address. This will display the location from where you are connected. Because I'm using a VPN in this scenario, it displays Madrid's location in Spain.
Let's return to the code snippets and see how we can incorporate this into our application. There are myriad languages such as C, Clojure, Go, Java, JavaScript, Kotlin, PHP, Python, R, Ruby, etc. from which to choose. The default for Axios is Node.js
, but for this guide, we'll use (JavaScript) fetch
. We can now paste it into our JavaScript file by clicking the Copy Code button.
Let's see how this works. In this guide, we will obtain our geolocation data in order to determine the city of our users. Then we'll pass that city to another API, which will provide us with weather data for that city.
We're going to use vite
to get this up and running quickly and install it in the current directory.
sh
npm init @vitejs/app
After that, we will give the package name rapidapi-demo
. For Select a framework
, we can choose vanilla JavaScript.
Once the above process is executed, we can install packages by simply using the following command:
sh
npm i
Considering that we'll be using Tailwind, we can install this by typing:
sh
npm i -D tailwindcss@latest
The files we need for Tailwind will then be created. Thus, we can say:
sh
npx tailwindcss init -p
Then, in tailwind.config.js
, we will specify the files we want to purge
when we build.
js
module.exports = {purge: ['./index.html', './**/*.js'],darkMode: false, // or 'media or 'class'theme: {extend: {}},variants: {extend: {}},plugins: []};
Following that, we'll import our tailwind details in the styles.css
.
css
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;}
Let's get started on the 'index.html' file. Change the title to RapidAPI Demo
. I've also included some HTML code here.
html
<!DOCTYPE html><html lang="en"><head><meta chorset="UTF-8" /><link rel="icon" type="image/svg+xml" href="favicon.svg" /><meta name="viewport" content="width-device-width, initial-scale=1.0" /><title>RapidAPI Demo</title></head><body class="bg-gray-100"><h1 class="text-bold text-6xl text-center p-8">Mixed API Feed</h1><divid="app"class="min-h-screen flex flex-col justify-center items-center gap-2"></div><script type="module" src="/main.js"></script></body></html>
In the code excerpt above, we've used a number of Tailwind classes, and we've also made a header that states Mixed API feed.
The weather data will be imported in the following steps. After that, we will add all the data to the div
with the id
of app
. So that is fairly easy. The main.js
file will be used for everything else.
Open up our main.js
file and take out the JavaScript that comes with VITE
. After that, we'll configure our function so that we can quickly use it with different APIs. We'll need to have our RapidAPI key available first. Therefore, we'll import that from an environmental variable and VITE
. However, we must add the VITE_
prefix to environmental variables if we want the client to see them.
js
import './style.css'const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;
We'll now make a new .env file, name it VITE_RAPIDAPI_KEY
, and set its value to our API key. From our code snippet at our RapidAPI dashboard, we may copy the RapidAPI key. Since it is a private key, I will update it before posting this manual.
js
VITE_RAPIDAPI_KEY=your-rapidapi-key
The next step is to set up a function called getData
, which will be an async
function. It will accept two parameters: a host and a URL. The URL will then be fetched after we construct a response variable that will await
and fetch
. We'll have a 'GET' method inside of it, followed by some headers. We will accept 'application/json', and our RapidAPI key and RapidAPI host will be passed.
After that, we'll determine if the response is okay and throw an Error
if it isn't. We'll end by returning await response.json
. Therefore, we can connect to various APIs using our RapidAPI key using this function.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};
The following step is to link this to the IP Geo Location API. We can accomplish this by defining two variables: GEOLOCATION URL
and GEOLOCATION HOST
.
This information can be obtained from our code snippet at RapidAPI Hub. We'll copy and paste the RapidAPI Host and RapidAPI URL from the code snippet into the main.js
file. This is how we'll set the values for our GEOLOCATION URL
and GEOLOCATION HOST
.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL = 'https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};
Let's create the main function that will call our APIs. We'll create a function called runAPIQueries
, which will be an async
function. We'll write the city name here and create a variable called geoData
. This will await
our getData
function we created earlier.
In the getData
function, we'll pass in our GEOLOCATION URL
and GEOLOCATION HOST
. The data will then be console.log
to see what we get. We also need to start the function we'll call at the end here.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);};runApiQueries();
Let's run this and see what we come up with. Open the terminal and type:
sh
npm run dev
On http://localhost:3000/
, we can see that a host server is running. When we open that, we'll see our Mixed API feed header. The outcome of the API call will be displayed on the console. There is an object, and if we open it, we will find the city key we seek. It contains the name of the city.
Let's now use a weather API to get weather information for the city. Let's go back to RapidAPI and look for the weather. We'll use Open Weather API, so open it up; all we need is the URL and the host information. We'll copy these and pass this information into our runAPIQueries()
.
Let's open our weather app, and we can copy the URL and Host information from the code snippet. We will go back to the main.js
file and add two variables i.e., const WEATHER_URL
and const WEATHER_HOST
. To incorporate weather information, we can write const weatherData
and make it equal to await getData()
inside the runApiQueries
function.
Now, we need to pass in our geolocation URL and our host. We can do this by adding our Weather_URL
and append to that with geo data.city.name
.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const WEATHER_URL = 'https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);};runApiQueries();
The next step is to update the UI with the console data. We'll go back to VSCode and create a constant called app
to get the app
id element. . This is the element where we will add our UI data. We will then set the innerHTML
of the app
constant to write HTML. We have added a div that has several Tailwind classes. Then within that, we're going to have our weatherData.weather[0]main
.
After that, we will add weather temperature followed by weather description. This is where it gives weather information such as partly cloudy with a chance of rain or something like that. Then we have an svg
and our weatherData.name
, which will be the city name. Following this, we will pull in the weather data and icon, showing a rain cloud, a sun, or whatever the current condition is.
jsx
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const WEATHER_URL = 'https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="flex bg-blue-500 text-white rounded py-2 px-8 w-full max-w-2xl items-center border-2 border-blue-300 shadow-lg"><div class="flex flex-col flex-grow"><div class="text-md">${weatherData.weather[0].main}</div><div class="flex h-max items-center"><div class="font-medium text-6xl">${parseInt(weatherData.main.temp)}°</div><divclass="flex flex-col ml-4 pl-4 border-l-2 border-blue-400"><div>${weatherData.weather[0].description.toUpperCase()}</div><div class="flex"><svgxmlns="http://www.w3.org/2000/svg"class="h-5 w-5"viewBox="0 0 20 20"fill="currentColor"><pathfill-rule="evenodd"d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"clip-rule="evenodd"/></svg><span class="pl-1">${weatherData.name}</span><div></div></div></div><imgclass="self-center inline-flex items-center justify-center rounded-lg h-28 w-28"src="http: //openweathermap.org/img/wn/${weatherData.weather[0].icon}@a2x. Png"alt="weather icon"/></div></div></div>`;};runApiQueries();
Let's go ahead and save that, and we'll go back to our app and see if it works. We can see information such as clouds, current temperature, and location successfully deployed in our feed.
Let's add another API to the app. We can do something a little more fun this time. If we write Chuck Norris, it will give us Chuck Norris API that provides us with some Chuck Norris jokes.
Like the previous API, we will copy the URL and Host information from Code Snippet and go back to VSCode.
Let's create some variables for those and paste the information we copied from the Code snippet. We want a random joke under the category of dev
. It will be very similar to the way we did the weather data. After that, we have to create a variable called chuckData
. It will be equal to getData
, which we will await. Then we will pass in our CHUCK_NORRIS_URL
and our CHUCK_NORRIS_HOST
and console.log
the data.
Once we get the data, we'll update the UI. We'll add our chuckData.icon_url
and then our chuckData.value
, which will be the joke we are looking for.
jsx
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com ';const WEATHER_URL ='https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const CHUCK_NORRIS_URL ='https://matchilling-chuck-norris-jokes-vl.p.rapidapi.com/jokes/random? category=dev';const CHUCK_NORRIS_HOST = 'matchilling-chuck-norris-jokes-v1.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="flex bg-blue-500 text-white rounded py-2 px-8 w-full max-w-2xl items-center border-2 border-blue-300 shadow-lg"><div class="flex flex-col flex-grow"><div class="text-md">${weatherData.weather[0].main}</div><div class="flex h-max items-center"><div class="font-medium text-6xl">${parseInt(weatherData.main.temp)}°</div><divclass="flex flex-col ml-4 pl-4 border-l-2 border-blue-400"><div>${weatherData.weather[0].description.toUpperCase()}</div><div class="flex"><svgxmlns="http://www.w3.org/2000/svg"class="h-5 w-5"viewBox="0 0 20 20"fill="currentColor"><pathfill-rule="evenodd"d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"clip-rule="evenodd"/></svg><span class="pl-1">${weatherData.name}</span><div></div></div></div><imgclass="self-center inline-flex items-center justify-center rounded-lg h-28 w-28"src="http://openweathermap.org/img/wn/${weatherData.weather[0].icon}@a2x.png"alt="weather icon"/></div></div></div>`;// GET - CHUCR NORRIS JOKESconst chuckData = await getData(CHUCK_NORRIS_URL, CHUCK_NORRIS_HOST);console.log(chuckData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="max-w-2xl w-full bg-purple-400 border-2 border-gray-300 shadow-lg p-6 rounded-md tracking-wide"><div class="flex items-center mb-4"><img alt="avatar" class="W-20" src="${chuckData.icon_url}" /><div class="leading-5 ml-6 sm"><h4 class="text-xl font-semibold">Chuck Norris</h4><h5 class="font-semibold text-purple-800">Boss</h5></div></div><div class="text-center"><q class="italic text-white text-lg">${chuckData.value}</q></div></div>`;};runApiQueries();
Let's save that, and we'll have access to our weather data, as well as this hilarious Chuck Norris joke.
It is time to add one more API. Let’s return to the RapidAPI Hub and search for “NewsData API”. We will use this NewsData API and integrate it with the previous three APIs.
Again, we just need to get its URL and host. We'll copy this information from the code snippet and paste it into VSCode inside two new variables.
Back in the main function under the chuck data, we will create another constant called newsData
and assign getData
to it, which we will await
Then we pass in our URL, and our host, and finally, we're going to console.log
the data. Let’s go back to our app and look at the API response in the console.
Since the news data is an array, we'll do forEach
through which we will get each article
, which we'll add to our inner HTML of the app. For the article
, we'll get the media_url
to get that cover image. Then after that, we'll get our title
and remember it had paragraph tags, which we'll remove.
We'll do the same for the excerpt, and that should be it.
jsx
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com ';const WEATHER_URL ='https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const CHUCK_NORRIS_URL ='https://matchilling-chuck-norris-jokes-vl.p.rapidapi.com/jokes/random? category=dev';const CHUCK_NORRIS_HOST = 'matchilling-chuck-norris-jokes-v1.p.rapidapi.com';const NEWS_URL = 'https://newsdata2.p.rapidapi.com/sources';const NEWS_HOST = 'newsdata2.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="flex bg-blue-500 text-white rounded py-2 px-8 w-full max-w-2xl items-center border-2 border-blue-300 shadow-lg"><div class="flex flex-col flex-grow"><div class="text-md">${weatherData.weather[0].main}</div><div class="flex h-max items-center"><div class="font-medium text-6xl">${parseInt(weatherData.main.temp)}°</div><divclass="flex flex-col ml-4 pl-4 border-l-2 border-blue-400"><div>${weatherData.weather[0].description.toUpperCase()}</div><div class="flex"><svgxmlns="http://www.w3.org/2000/svg"class="h-5 w-5"viewBox="0 0 20 20"fill="currentColor"><pathfill-rule="evenodd"d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"clip-rule="evenodd"/></svg><span class="pl-1">${weatherData.name}</span><div></div></div></div><imgclass="self-center inline-flex items-center justify-center rounded-lg h-28 w-28"src="http://openweathermap.org/img/wn/${weatherData.weather[0].icon}@a2x.png"alt="weather icon"/></div></div></div>`;// GET - CHUCR NORRIS JOKESconst chuckData = await getData(CHUCK_NORRIS_URL, CHUCK_NORRIS_HOST);console.log(chuckData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="max-w-2xl w-full bg-purple-400 border-2 border-gray-300 shadow-lg p-6 rounded-md tracking-wide"><div class="flex items-center mb-4"><img alt="avatar" class="W-20" src="${chuckData.icon_url}" /><div class="leading-5 ml-6 sm"><h4 class="text-xl font-semibold">Chuck Norris</h4><h5 class="font-semibold text-purple-800">Boss</h5></div></div><div class="text-center"><q class="italic text-white text-lg">${chuckData.value}</q></div></div>`;// GET NEWS DATAconst newsData = await getData(NEWS_URL, NEWS_HOST);console.log(newsData);newsData.forEach(article => {app.innerHTML += /*html*/ `<div class="max-w-2xl w-full flex border-2-border-gray-300-shadow-lg"><imgclass="h-autow w-48 flex-none rounded-l object-cover"src=${article.jetpack_featured_media_url}alt="Image Description"/><divclass="bg-white rounded-r p-4 flex-flex-col justify-between leading-normal"><div class="mb-0"><div class="text-black font-bold text-xl mb-0">${article.title.rendered.replace('<p>', '').replace('</p>', ' ')}</div><pclass="text-grey-darker text-sm overflow-hidden overflow-ellipsis may-h-24">${article.excerpt.rendered.replace('<p>', ' ').replace('</p>', ' ')}</p></div></div></div>`;});};runApiQueries();
Let's go ahead and save it and go back to the app.
All right. We have our Weather, Chuck Norris, and our NewsData APIs.
This is how using RapidAPI, we have successfully implemented four different APIs quickly and easily using a single API key and a single management dashboard.
Nowadays, there is an API for almost everything. Let me demonstrate how you may create your own API and earn money. There are four interrelated categories that can be used to categorize the concept of developing and selling APIs.
The first category, IDEA, is the most difficult because it requires the creation of an API that solves a real-world problem. It is commonly used by developers who create APIs to solve problems that can be sold to other developers who are experiencing similar problems. Following the IDEA, the other categories—namely, building, hosting, and selling—are possibly the simplest.
To demonstrate the procedure and offer you an example, I'll construct a very simple API. I'm going to create an API that enables you to play rock, paper, scissors.This will be built using JavaScript and CloudFlare Workers, enabling us to host API for no cost. The following steps will simplify the task:
We can begin by installing the CLI tool wrangler, which is designed for Cloudflare Workers users. It can be installed via terminal with the following command:
sh
npm i -g @cloudflare/wrangler
The next step is to log in to your wrangler account via the terminal. To complete this step, you must first sign up for your CloudFare.
sh
wrangler login
Following that, we return to the terminal and run wrangler to generate Rock, Paper, Scissor.
sh
wrangler generate rock-paper-scissors
Open the project in your code editor at this point. To launch the project in VS Code, type the following command in your terminal:
sh
code rock-paper-scissors
When we open VS Code, we must enter the account id into a wrangler.toml
file. This account number can be found in your CloudFlare Workers dashboard. To demonstrate, we will use a hypothetical one that will not work if you are not properly logged in.
toml
name = "rock-paper-scissors"type = "javascript"account_id = "94a03164bdf96ae6281fac89feb0c91a"workers_dev = trueroute = " "zone_id = " "
We have a paper that beats a rock, scissors that beat a paper, and scissors that beat a rock, which is just an array of objects.
In VS Code, we navigate to index.js
and begin defining our options, including information about which choice beats which. The addEventListener()
function is attached to an event handler in the following code snippet. We will create an actual API using the knowledge gained above.
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 is to get a 'searchParams' that will be passed to the API. So, when we call the API from our client, we give the API user's preference by passing it in a 'searchParams'.
This 'searchParams' will be a choice, so we will use the following command to request a choice from our 'searchParams':
js
const requestChoice = searchParams.get(choice);
The next step is to determine our choice based on our choices definition. This way, we would know the choice name and what it beats.
js
const userChoice= CHOICES.find((choice) => choice.name === requestChoice);
As you can see, we are comparing our parameters of choice. This response will be used to return the client results.
Instead of returning Hello worker!
, we'll write a getResults()
function that takes the user choice and the random choice. We'll also remove text/plain
and replace it with application/jason
. This is how we will proceed.
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' },});}### Step 9We now proceed to the `getRandom` function, which will return a random choice from the worker or the AI. `Math.Random` will be multiplied by 'CHOICES.length'. Because there are only three options, we will get a random number between 0 and 2.```jsfunction 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];}
We will now 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 whether the user wins by calling the function 'isWinner' and inputting our options. This simple function will now be defined. We'll write the function 'isWinner' and present 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;}
Knowing that the user is the first choice, we will assess whether the user beats the AI. However, we must also determine whether AI can beat the users. This is what we'll write:
js
aIWins = isWinner ()
We need to reverse the array here because we don't want to affect the array itself. Considering that we will be using the array again later, we will therefore use the spread operator to create a copy of it. This will return back to us whether the AI wins or not. 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 put this to the test right now with Wrangler. So we'll open a terminal, type $wrangler dev
, and we'll 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'll create a new project, and we'll just call it Rock, Paper, Scissors, and then start working on it.
We're going to make a new request here. We'll type in http://127.0.0.1:8787 as our localhost. We'll need to add a query with the choice parameter, and for value, we can type 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.
Every time we change the value, we'll get a new response. This time, we chose rock, and the AI chose rock, so it's a tie. If we change this from rock to paper, and the AI chooses rock, we will win this time. Every time we change the value, we'll get a new response.
Because we built this with CloudFlare workers, we can easily host our API, even for free, unless we receive a large amount of traffic. We only need to run wrangler publish
to deploy this API. So, let's try it from Paw with our newly deployed URL. So that rock-paper-scissors.codestacker.workers.dev
, and we can experiment with different responses and see how they turn out.
It's time to sell our API and start dealing in cash. To quickly publish our API and monetize it, we will sign up for free on [RapidAPI Hub](https://RapidAPI.com/auth/sign-up?utm source=RapidAPI.com/guides&utm medium=DevRel&utm campaign=DevRel).
After registering, navigate to My APIs and add a new API there. In this field, a brief description must be entered. For example, we may write, "Play Rock, Paper, Scissors via API." We might choose the category "Gaming" and then add API.
Create a long description that best describes your game API. Alternatively, you can add a logo and a website, and we'll set the category for you. We do not have any terms of service. We'll just save it there.
The next step is to click configure and specify the Base URL. We can write Base URL as "https://rock-paper-scissors.codestacker.workers.dev".
The third step is to add an Endpoint. It will be a REST endpoint. So we'll click that, and we can call this Choice and describe it as User's choice. Alternatively, we can provide some documentation, which is always beneficial.
Following that, we have our query parameters. Assume that our query parameter is choice. We can see below that we have some sample code that we can run and test. We have the option of changing the language. Let's go straight to JavaScript fetch.
This is how it would appear. So notice how it refers to RapidAPI's API rather than our actual API. So we can put our API on the marketplace without users seeing the actual endpoint. Let's save now to test this endpoint.
We need to test the endpoint, and we can see some responses here. We got our user, who chose rock, and AI chose rock; the result was a tie. We can see that it is functioning.
We can create an example from this response so that whenever someone looks 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 it.
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 is typically used by a developer to test something. However, if they begin to use it in production, you want them to upgrade to a paid plan. Let's save this now, and we can also add a pro plan. For example, on the pro plan, it could be $10/month, and we'd rate limit it. We'll set a soft limit of 100000 requests per month for the pro plan. Similarly, we can add more plans, such as an Ultra Plan or a Mega Plan.
Our API is now available at the hub. Now that we have fulfilled all the conditions, we may make it public. In the DANGER ZONE, we must change API Visibility 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.
We can view its details once we open the necessary API. In this scenario, we can observe our recently developed Rock Paper Scissor API.
So that's it, everyone! A Rock, Paper, Scissor API that we created has been deployed, published on RapidAPI Hub, and enabled for monetization. So go ahead and give it a shot and create some fantastic new APIs.