REST API CRUD Example in PHP and MongoDB

In this tutorial I am going to show an example on REST API CRUD example in PHP and MongoDB. We know MongoDB is very popular open source, document based, NoSQL database. In this tutorial I will create MongoDB PHP CRUD Example with RESTful API.

CRUD means Create, Read, Update and Delete operations. So basically you will add new data (create), fetch data (read), edit existing data (update) and remove existing data (delete) from database.

REST or RESTful API is now most popular framework due to its performance, support of multiple media types (text, html, json etc.) with many more other features.

Here I will create REST services in PHP programming language and perform operations to read, insert, update and delete in MongoDB database. Here I will not create any table but if you want you can also create table to work as a relational database. But here I need to create at least one collection to store data.

Related Posts:

Let’s move on to the example…

Prerequisites

Apache HTTP Server 2.4, PHP 7.4.3, MongoDB 4.4.0, Postman or any REST Client Tool

MongoDB Installation in Windows

Configure MongoDB with PHP7 on Windows

Project Directory Setup

Preparing your workspace is one of the first things that you can do to make sure that you start off well. The first step is to check your MongoDB instance is working fine. Once you found MongoDB instance is running then you can try to connect to MongoDB server using MongoDB client where you check your collection, your data, you perform query etc. Then you can check your http server is working fine using xampp control panel.

When your above requirements are fulfilled then you need to write some PHP code in order to build REST API. So you need to first navigate to the directory <physical drive location>:/xampp/htdocs and create nested folders called php-mongodb-rest-api-crud and go inside it.

I may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

Now we will create several php files for our REST API CRUD example.

Database Connection

First and foremost thing is to connect to the MongoDB and here we are going to create a PHP class to establish the database connection for performing CRUD operation on it.

Create mongodb_config.php file and put below source code into it.

Below is the DbManager class that is responsible for establishing connection to MongoDB for our REST API CRUD example in PHP and MongoDB.

Here we have taken database host, port and connection objects as instance variable and through constructor we are trying to connect to the Mongo Database and for any failure we throw an exception.

We have added getConnection() function which will give you the connection object that will be actually used to perform the CRUD operation on Mongo database.

<?php

class DbManager {

	//Database configuration
	private $dbhost = 'localhost';
	private $dbport = '27017';
	private $conn;
	
	function __construct(){
        //Connecting to MongoDB
        try {
			//Establish database connection
            $this->conn = new MongoDB\Driver\Manager('mongodb://'.$this->dbhost.':'.$this->dbport);
        }catch (MongoDBDriverExceptionException $e) {
            echo $e->getMessage();
			echo nl2br("n");
        }
    }

	function getConnection() {
		return $this->conn;
	}

}

?>

REST Resource – Create

The first letter of CRUD operation indicates Create. Therefore I will create resource or data and store it into the MongoDB.

Create rest_resource_create.php file and copy below source code into it.

Here notice we have added few headers but three important headers are:

"Access-Control-Allow-Origin: *" – it indicates the request is accepted from any where

"Content-Type: application/json; charset=UTF-8" – it indicates that request is a json data

"Access-Control-Allow-Methods: POST" – it indicates that only POST request is allowed

Next we need DbManager class, so we included mongodb_config.php file in it. Then we define database name and collection name for performing query.

We create new DbManager() object and get the connection object.

Next we read the json request data using the following line:

$data = json_decode(file_get_contents("php://input", true));

php://input is a read-only stream that allows you to read raw data from the request body.

Then we create BulkWrite() instance and insert the json request data into Mongo database using executeBulkWrite() method.

As I had told previously that we are not creating any relational database here so we are directly inserting the json data into MongoDB.

<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database file
include_once 'mongodb_config.php';

$dbname = 'roytuts';
$collection = 'users';

//DB connection
$db = new DbManager();
$conn = $db->getConnection();

//record to add
$data = json_decode(file_get_contents("php://input", true));

// insert record
$insert = new MongoDB\Driver\BulkWrite();
$insert->insert($data);

$result = $conn->executeBulkWrite("$dbname.$collection", $insert);

// verify
if ($result->getInsertedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully created")
	);
} else {
    echo json_encode(
            array("message" => "Error while saving record")
    );
}

?>

Testing the Application

We have written enough code for creating resource in REST API CRUD example in PHP and MongoDB and it’s time to test the application. So here we will use the REST client for testing Create operation.

rest api crud example in php and mongodb

Now check the MongoDB using the command db.users.find(), you will find one record successfully inserted:

rest api crud example in php and mongodb

REST Resource – Read

Now we will see how Read operation in CRUD example works.

Create rest_resource_read.php file and put the below source code into it.

Here also we have added few headers and response data in json. We have not added any http method, so by default the htpp method is GET request.

Notice in this file we have filter[] and option[] array which are used to restrict the query to select the records based on filter and option values.

We use here executeQuery() method to read the data from MongoDB.

We display the as json format and as query returns multiple rows, so we are using here iterator_to_array() method to iterate the json array.

<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database file
include_once 'mongodb_config.php';

$dbname = 'roytuts';
$collection = 'users';


//DB connection
$db = new DbManager();
$conn = $db->getConnection();

// read all records
$filter = [];
$option = [];
$read = new MongoDB\Driver\Query($filter, $option);

//fetch records
$records = $conn->executeQuery("$dbname.$collection", $read);

echo json_encode(iterator_to_array($records));

?>

Testing the Application

Now it’s time to test the Read operation in CRUD example.

rest api crud example in php and mongodb

REST Resource – Update

Now we will see how to work on Update operation of REST API CRUD example in PHP and MongoDB.

Create rest_resource_update.php file with below source code.

In the below file also we have added few headers as we added for create operation but only one difference is that we have added here http PUT method for client’s request.

We are reading the request json in the same way we read for create operation.

We build the update array and where clause for performing update operation.

Finally we execute the query using executeBulkWrite() method. Then we verify the update result and display the result.

<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: PUT");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database file
include_once 'mongodb_config.php';

$dbname = 'roytuts';
$collection = 'users';

//DB connection
$db = new DbManager();
$conn = $db->getConnection();

//record to update
$data = json_decode(file_get_contents("php://input", true));

$fields = $data->{'fields'};

$set_values = array();

foreach ($fields as $key => $fields) {
	$arr = (array)$fields;
	foreach ($fields as $key => $value) {
		$set_values[$key] = $value;
	}
}

//_id field value
$id = $data->{'where'};

// update record
$update = new MongoDB\Driver\BulkWrite();
$update->update(
	['_id' => new MongoDB\BSON\ObjectId($id)], ['$set' => $set_values], ['multi' => false, 'upsert' => false]
);

$result = $conn->executeBulkWrite("$dbname.$collection", $update);

// verify
if ($result->getModifiedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully updated")
	);
} else {
    echo json_encode(
            array("message" => "Error while updating record")
    );
}

?>

Testing the Application

Now it’s time to test the update operation of REST API CRUD example in PHP and MongoDB.

Basically here we are updating here first name and last name for the given _id.

rest api crud example in php and mongodb

Now check the database. You see the first name and last name have been updated successfully.

rest api crud example in php and mongodb

REST Resouce – Delete

Finally we will see example of Delete operation of CRUD management.

Now create rest_resource_delete.php file and put the below source code into it.

We have added http DELETE method for delete operation.

<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database file
include_once 'mongodb_config.php';

$dbname = 'roytuts';
$collection = 'users';

//DB connection
$db = new DbManager();
$conn = $db->getConnection();

//record to delete
$data = json_decode(file_get_contents("php://input", true));

//_id field value
$id = $data->{'where'};

// delete record
$delete = new MongoDB\Driver\BulkWrite();
$delete->delete(
	['_id' => new MongoDB\BSON\ObjectId($id)],
	['limit' => 0]
);

$result = $conn->executeBulkWrite("$dbname.$collection", $delete);

//print_r($result);

// verify
if ($result->getDeletedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully deleted")
	);
} else {
    echo json_encode(
            array("message" => "Error while deleting record")
    );
}

?>

Testing the Application

Let’s test the delete operation:

rest api crud example in php and mongodb

Now check the database. So finally we have successfully deleted the record.

rest api crud example in php and mongodb

Congratulations! Hope you got an idea on REST API CRUD example in PHP and MongoDB.

Source Code

Download

Thanks for reading.

3 thoughts on “REST API CRUD Example in PHP and MongoDB

  1. Super, funciona al 100% y en mi primer intento.
    lo probé con las siguientes versiones:

    PHP Zend Engine v3.4.0
    MongoDB 3.6.8
    Apache 2.4.41

    Muy bien explicado, Muchas gracias por el tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *