REST API in Slim 3 Framework – Part 1
…Continued from previous page. Go to Table of Contents.
The common approach when installing Homestead is to do so globally. The major drawback with this approach is continually editing the Homestead YAML configuration and re-provisioning your VM with each site added to your portfolio.
The approach I’d rather use is installing Homestead on a per-project basis. Each project then has it’s own Homestead YAML config file that is tracked in version control, so when adding new developers to a project, they can provision the exact same VM that you’re using.
NOTICE: As mentioned earlier, when working with virtual machines, you need to have your computer correctly configured for virtualisation.
$ composer require laravel/homestead --dev $ vendor/bin/homestead make
This next step helps us get around some common issues that others have had. It’s helped me to do this as well… Edit your VagrantFile to include the following lines to the end of your
config.vm.provider 'virtualbox' do |vb| vb.customize ['modifyvm', :id, '--cableconnected1', 'on'] end
/etc/hosts file to include the ip address and sites.map value listed in your
Homestead.yaml. In my case this is:
The first time you start your Vagrant box it will take a while as it downloads the operating system and all the tooling required. Subsequent starts will only take a few seconds.
To start Homestead:
$ vagrant up
Once your box is running, go to your browser and test out your URL (whatever was in your Homestead.yaml under sites->map. For me that’s homestead.test
To stop Homestead:
$ vagrant halt #stops the vagrant machine $ vagrant suspend #suspends a virtual machine (remembers state)
Convert to API
Since all we want is an API, not a whole web app, we can do away with rendering templates and just return JSON. We’ll do all the cleanup in a later blog post — for now we’ll just have the router return a JSON response instead of rendering a web page.
To do this, open
src/routes and replace the return statement with the following:
// Render index view $salutation = isset($args["name"]) ? $args["name"] : 'world'; return $response->withJson(['hello' => $salutation]);
Now refresh the web page and you should see JSON.
We covered a lot of ground in this tutorial in order to get through all the one-time configurations. We got some minimal tooling installed, created a Slim application and made it portable with Homestead. Now that you’re all set up, you can apply these techniques to quickly building other web apps and API’s.
In future instalments we’ll go deeper into the router, we’ll look at middelware, we’ll add authentication, we’ll connect to a database and so much more.