APIs are being used everywhere to build web apps. They have different types and multiple use cases. One of the most common ones would be to use an API to get data from the server.
We can develop a web application in different languages. For instance, there is JavaScript, Python, PHP, Ruby, etc. We can go a step further and use frameworks of these languages. Just like this, we can also develop RESTful APIs in different languages.
In this piece, let’s look at how to build an API using JavaScript, Python, and PHP. We will also test the API using the RapidAPI Client while we are building it. So without any further ado, let’s jump in!
JavaScript is a programming language that is vastly used to build web applications. Before Node.js, JavaScript was mainly used on the client side. But now, it is used on the server as well.
Over time, the developers created several libraries and frameworks using JavaScript. One of them is Express, a backend Node.js framework used to set up a Node.js-based server. It is minimal and flexible and provides a robust set of features for web and mobile applications. You can use it to create routes, middleware, and everything else you need in a server.
We will now use Express to create our RESTful API.
Let’s build an API in simple steps to make it easier to follow.
The first thing we need to do is install Node. You can skip this step if you already have it installed. Otherwise, you can find the latest version here. Once you download it, go ahead and install it on your computer.
We will also be using the RapidAPI Client to test the APIs as we develop them. So make sure you install it in your VS Code.
Create a directory on your computer and open it in your preferred code editor. We need to create package.json
to hold our API’s metadata. So let’s go ahead and do it.
Once you create the file, please go ahead and copy-paste the following code there:
json
{"name": "movies-api","version": "1.0.0","description": "","main": "index.js","keywords": [],"author": "","license": "ISC"}
Just replace the value of name
key with your preferred API name. Moreover, you can create the same file by running the following command in your project terminal:
sh
npm init -y
Earlier, we discussed Express, a JavaScript server-side framework built on top of Node. Let’s go ahead and install it inside our project. Like before, open your project terminal again and run the following command:
sh
npm install express
We will also install nodemon
as a developer dependency. With nodemon
, we do not have to exit the server and start it again every time we make a change.
sh
npm install -D nodemon
Lastly, we need to create a scripts
key in our package.json
file. It will be an object that will take key/value pairs. The following is the updated package.json
file:
json
{"name": "movies-api","version": "1.0.0","description": "","main": "index.js","keywords": [],"author": "","license": "ISC","dependencies": {"express": "^4.18.1"},"scripts": {"server": "nodemon index.js"},"devDependencies": {"nodemon": "^2.0.19"}}
The version number of the dependencies might be different when you install them.
Go ahead and create an index.js
file inside the project directory. Now import Express inside it.
js
//commonjs syntaxconst express = require('express');//or// ES6 syntaximport express from 'express';
Let’s create an Express application by writing the following piece of code.
js
const app = express();
Now we need to add a middleware so that our server can recognize the incoming request as a JSON object.
js
app.use(express.json());
Lastly, we need to listen for a connection.
js
const port = process.env.PORT || 5500;app.listen(port, () => console.log(`Listening on Port: ${port}`));
The following is what the file will contain when you are done:
js
const express = require('express');const app = express();// middlewareapp.use(express.json());// portconst port = process.env.PORT || 5500;app.listen(port, () => console.log(`Listening on Port: ${port}`));
Let’s ensure that the codebase of the API we are developing is modularized. So, create a routes directory inside the project directory. Now create a movies.js
file inside the routes
directory and copy-paste the following code there:
js
// importing packagesconst express = require('express');const router = express.Router();const movies = [{id: 1,name: 'The Terminal',year: 2004,rating: 7.4,},{id: 2,name: 'The Outfit',year: 2022,rating: 7.1,},{id: 3,name: 'The Godfather',year: 1972,rating: 9.2,},{id: 4,name: 'The Godfather: Part II',year: 1974,rating: 9.0,},{id: 5,name: 'The Godfather: Part III',year: 1990,rating: 7.6,},{id: 6,name: 'Uncharted',year: 2022,rating: 6.3,},];router.get(`/`, function (req, res) {res.status(200).json(movies);});router.post(`/`, function (req, res) {const { name, year, rating } = req.body;res.status(200).json([...movies, { id: movies.length + 1, name, year, rating }]);});router.delete(`/`, function (req, res) {const { id } = req.body;res.status(200).json(movies.filter(movie => movie.id !== id));});module.exports = router;
I have exported Express in this file and used it to create a router. Afterward, I defined a sample movies array and wrote three router functions to handle the GET
, POST
, and DELETE
requests. I have passed a callback function as the second parameter to send a response to the client in each of these functions.
Lastly, I am exporting the router I have just created from this file.
Let’s import our movies
route inside index.js
.
js
const movie = require('./routes/movie');
Now register this route in your application like this:
js
app.use('/movie', movie);
The functions inside the movie.js
file will run when the client requests the /movie
endpoint with an appropriate HTTP method. For instance, https://baseURL/movie
.
The code in the index.js
file will look like this in the end:
js
const express = require('express');const movie = require('./routes/movie');const app = express();// middlewareapp.use(express.json());app.use('/movie', movie);// portconst port = process.env.PORT || 5500;app.listen(port, () => console.log(`Listening on Port: ${port}`));
Let’s use the RapidAPI Client to test the API we have developed. Before we do this, we need to start the server by running the following command inside the project terminal.
sh
npm run server
This will start our server at http://localhost:5500
.
Now open the RapidAPI Client and create a new request by clicking on the (+) icon.
Let’s test our GET
request. To do that, add the http://localhost:5500/movie
inside the API URL input box and click the Send button. If the request is successful, we will see a status 200 and an array of movies.
Similarly, we can test the POST
and DELETE
HTTP methods on the API. Change the HTTP method to POST
. Let’s provide the following request body to the POST
request.
json
{"name": "The Mummy","year": 1999,"rating": 7.1}
Click on the Send button. You will see that the data has been updated.
Lastly, we can test the DELETE
endpoint by providing the movie's id inside the request body and clicking on the Send button.
Here is a quick demo of how you can test your API.
We have successfully developed an API using JavaScript and tested it using the RapidAPI Client for VS Code.
Python is another extremely powerful programming language that can be used to build web applications, write machine learning algorithms, artificial intelligence, etc. It also provides different frameworks and libraries to make development easier and more efficient. One such framework is Flask which is used to build backend architecture.
Flask is a lightweight Python micro-framework that lets you create an app using a single file. It does not require the developer to follow a particular directory structure and provides features like URL routing, template engine, etc.
Let’s build an API in simple steps to make it easier to follow.
Just like with Node, we need to install Python on our computers. You can download its latest version from here. Once downloaded, go ahead and install it on your computer.
Create a directory on your computer and open it inside your preferred code editor. Now we need to set up a virtual environment. It will ensure that our packages are not installed globally.
So let’s install the virtualenv
package on our computer using the following command:
sh
pip install virtualenv
This command will globally install virtualenv
package on your computer. After its done installing, run the following there:
sh
virtualenv env
It will create an env directory with your virtual environment files. There is no need to change and open any files in the virtual environment.
There are different commands to activate the virtual environment on Linux and Windows. Choose the command from below that fits the bill for you:
sh
# for windowssource env/Scripts/activate# for linuxsource env/bin/activate
Ensure you activate the virtual environment by running the command according to your operating system. The virtual environment needs to be activated for the entire span of your development process.
Now it’s time to install Flask
and flask_cors
packages in our project. For this, run the following commands in your project terminal:
sh
pip install Flask flask_cors
Create an app.py
file in the project directory and import Flask
and Flask_cors
packages at the top.
py
# importing packagesfrom flask import Flaskfrom flask_cors import CORS
Now set up a Flask app and enable CORS by adding the following piece of code in your app.py
file:
py
# APP SETUPapp = Flask(__name__)# enable resource sharing between frontend and serverCORS(app)
Lastly, let’s create a song
route that will provide us with different song information.
py
# IMPORTfrom flask import Flaskfrom flask_cors import CORSfrom flask import jsonifyfrom flask import request# APP SETUPapp = Flask(__name__)# enable resource sharing between frontend and serverCORS(app)songs = [{"id": 1,"title": "Danza kuduro","artist": "Don Omar",},{"id": 2,"title": "Despacito","artist": "Luis Fonsi",},{"id": 3,"title": "Shape of you","artist": "Ed Sheeran",},{"id": 4,"title": "Havana","artist": "Camila Cabello",},{"id": 5,"title": "I Ain't Worried","artist": "OneRepublic",}]# ROUTES@app.route('/song', methods=['GET'])def getSong():return jsonify(songs)@app.route('/song', methods=['POST'])def postSong():data = request.get_json()id = len(songs) + 1data['id'] = idsongs.append(data)return jsonify(songs)@app.route('/song', methods=['DELETE'])def deleteSong():data = request.get_json()id = data['id']for song in songs:if song['id'] == id:songs.remove(song)return jsonify(songs)if __name__ == "__main__":app.run(debug=True)
You can see that I have created a python list; inside it, there are multiple dictionaries. Each dictionary contains song information. I have then handled GET
, POST
, and DELETE
HTTP methods and provided them a function to manipulate song data accordingly.
Now run the app by running the following command in your project terminal:
sh
python app.py
Now let’s test our API using RapidAPI Client. Open RapidAPI Client inside your VS Code and create a new request.
Our server runs on http://127.0.0.1:5000/
and we have a song
route. Go ahead and try to make a GET request to this route using RapidAPI Client. If the request is successful, you will receive an array of songs.
You can also test the POST
request and DELETE
HTTP method on the API using RapidAPI Client.
Here is a quick demo of how you can test your API.
We have successfully developed an API using Python and tested it using the RapidAPI Client for VS Code.
PHP is one of the oldest languages and is responsible for running over 75% of the internet. It is a server-side language adopted by the likes of Meta for their product “Facebook”. WordPress, which powers over 40% of the Internet, is written in PHP.
You can integrate several databases in PHP, including MySQL, PostgreSQL, Oracle, Sybase, etc. It is simple, efficient, and provides great flexibility when developing servers.
Let’s build an API in simple steps to make it easier to follow.
Just like we did with Node and Python, we first need to install PHP on our computer. You can download it from here. Once downloaded, please go ahead and install it.
Since PHP is server-side, we need to set up a server. You can use any server of your choice, but for this piece, I am using XAMPP.
Now navigate to where you have installed XAMPP. Inside it, you will find a directory called htdocs
. Create a folder inside this directory called book-api
. Now open this directory in your preferred code editor.
Create routes
directory inside your root directory. Inside routes
, create a file called books.php
. In this file, you will write the routes. For this, copy and paste the following code there:
php
<?phpheader( 'Access-Control-Allow-Origin: *' );// get request method$method = $_SERVER['REQUEST_METHOD'];$books = array(array('id' => 1,'title' => 'The Hobbit','author' => 'J.R.R. Tolkien','year' => 1937,),array('id' => 2,'title' => 'The Fellowship of the Ring','author' => 'J.R.R. Tolkien','year' => 1954,),array('id' => 3,'title' => 'The Two Towers','author' => 'J.R.R. Tolkien','year' => 1954,),array('id' => 4,'title' => 'The Return of the King','author' => 'J.R.R. Tolkien','year' => 1955,),);if ( $method == 'GET' ) {echo json_encode( $books );}if ( $method == 'POST' ) {$book = json_decode( file_get_contents( 'php://input' ) );$book->id = count( $books ) + 1;$books[] = $book;echo json_encode( $books );}
You can see that I have set the access control origin header to all. It means anyone can call this API. Afterward, I handled two HTTP request methods.
Let’s test our API now using the RapidAPI Client. Please ensure that your XAMPP server is running.
Open RapidAPI Client inside your VS Code and create a new request.
Our server runs on http://localhost/books-api/routes/book.php
with a book
route. Go ahead and make a GET
request to this endpoint using RapidAPI Client. If the request is successful, you will receive an array of books.
You can also add a book using the POST
HTTP method.
Here is a quick demo of how you can test your PHP API.
We have successfully developed a RESTful API using PHP.
That’s all, folks! If you want to learn more about RapidAPI Client and how to use it to test APIs inside VS Code, I recommend you look at this piece.