This tutorial shows 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 we will create MongoDB PHP 7 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 we will create REST services in PHP language and perform operations to read, insert, update and delete in MongoDB database. Here we will not create any table but if you want you can also creat table to work as a relational database. But here we have to create at least one collection to store data when we insert into MongoDB.

Before reading REST API CRUD example in PHP and MongoDB, you may need to configure the evironment in Windows(I am using Windows environment), so please read Configure MongoDB with PHP7 for XAMPP on Windows

You may like to read:

MongoDB PHP 7 CRUD Example

REST API CRUD Example in PHP, MySQL

Codeigniter REST + ReactJS CRUD Example

Let’s move on to the example…

Prerequisites

Knowledge of PHP and Database

Preparing your workspace

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.

If you want to use xampp package then please read Configure MongoDB with PHP7 for XAMPP on Windows

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/mongo and go inside it.

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

Establishing 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 db.php file under mongo directory 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 MongoDBDriverManager('mongodb://'.$this->dbhost.':'.$this->dbport);
        }catch (MongoDBDriverExceptionException $e) {
            echo $e->getMessage();
			echo nl2br("n");
        }
    }

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

}
?>

Creating Resource

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

Create create.php file under mongo directory 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 db.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 'db.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 MongoDBDriverBulkWrite();
$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, you will find one record successfully inserted

rest api crud example in php and mongodb

Reading Resource

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

Create read.php file under mongo directory 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 'db.php';

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


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

// read all records
$filter = [];
$option = [];
$read = new MongoDBDriverQuery($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

Updating Resource

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

Create update.php file under mongo directory 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 'db.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 MongoDBDriverBulkWrite();
$update->update(
	['_id' => new MongoDBBSONObjectId($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

Deleting Resouce

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

Now create delete.php file under mongo directory 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 'db.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 MongoDBDriverBulkWrite();
$delete->delete(
	['_id' => new MongoDBBSONObjectId($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.

You may like to read:

MongoDB PHP 7 CRUD Example

REST API CRUD Example in PHP, MySQL

Codeigniter REST + ReactJS CRUD Example

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

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

Leave a Reply

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