How to get REST web service to return record just added via POST

I have a REST web service in API Tools for CRUD of a database table (DB2 for i) where the (unique) key is an identity column called “order_id”. The route looks like this:

'route'    => '/sleep-order-header[/:order_id]',

Both the route identifier and entity identifier are 'order_id`

So if I want to fetch a single record, I’d use the URL “…/sleep-order-header/123” (to get order_id=123.

The problem is that, when creating the record (via POST), I don’t know the value of the key that will be created. So I have to call it with just ."…/sleep-order-header" (not passing the order_id). I also have to enable POST for Collections. Then it will call the create function in my SleepOrderHeaderResource. The problem is that it returns a collection of all the records in the table. I want it to return only the record last added I tried just retrieving the new record (or just the order_id of the record just created) and returning that in the create() function, but I still get the whole table.

Question: How can I force the POST to return just the one record just created?

If I understood correctly, you have a create method in your class (to create a record). After creating a record in the database, return the ID of the new record and then in the controller do a redirect.

Something like this:

public function create(Entity $entity)
	{
		$insert = new Insert('table_name');

		$insert->values([
			'column' => $entity->getValue(),
			...
		]);

		$statement = $this->db->prepareStatementForSqlObject($insert);
		$result = $statement->execute();

		if (! $result instanceof ResultInterface) {
			throw new RuntimeException(
				'Database error occurred during entity insert operation'
			);
		}

		$order_id = $result->getGeneratedValue();
		return $order_id;
	}

This way, when you add a record, the method will return the identifier of the newly created object and you can use it in the controller.

The issue is not adding the record. The issue is that in API Tools, when you create a REST web service, it creates a ___Resource file that is essentially your entry point (from an application point of view). In that Resource file there is a function called create() which gets called when you do a POST. I can get the record that I just added (using the TableGateways->getLastInsertValue(), and I can make that the return value of the create() function in the Resource, but it doesn’t matter what I return, API Tools returns a collection of all the records in the database.

Please check out this article. Maybe you will find something interesting:

I am not using Mezzio. I am using API Tools (formerly Apigility) - different framework.

Never mind. I figured it out. I had a typo. Just a dumb error. Funny how a little “!” can make all the difference in the world. Thanks for trying to help.

1 Like