Git Product home page Git Product logo

slim-api's Introduction

REST API with Slim, MongoDB, JWT

a RESTful API boilerplate for Slim framework

Build Status Software License Scrutinizer Code Quality codecov Packagist

Features

  • API CRUD with MongoDB Collection persistence. " KIS & VS" "Keep It Simple and Very Stupid"
  • JWT Authentication
  • Middleware "CORS, JWT"
  • Event Handling
  • Endpoint Tests and Unit Tests
  • CI - Travis CI

Directory Layout

.
├── app                    # Core code of the application.
│   ├── Base               # Contains base functionality of the framework
│   └── User               # Resource example for user
├── config                 # Framework configuration files are in this folder
│   └── settings.php       # Main configuartion of the framework.
├── public                 # Contains index.php file which is the entry point for requests
├── storage                # Contains the cache and files generated by the framework
│   └── logs               # Contains out application's logs files.
├── tests                  # Tests are placed in that folder.
├── vendor                 # Contains dependencies handled by composer.
├── CONTRIBUTING.md        # This file guide you how to contribute to this repo.
├── LICENSE.md             # License file for api.
├── README.md              # Introduces our api to user.
├── composer.json          # This file defines the project requirements
└── phpunit.xml            # Contains the configuration for PHPUnit.

Getting Started

First, clone the repo:

git clone https://github.com/me-io/slim-api

Install dependencies

cd slim-api
composer install

Configure the Environment

Create config/ext.settings.php file:

// override any default settings
return []

If you want you can edit database name, database username and database password.

Run Application

To start making RESTful requests to slim-api start the PHP local server using:

php -S 0.0.0.0:3500 -t public

Creating token

For creating token we have to use the http://localhost:3500/api/user/login route. Here is an example of creating token with Postman.

Imgur

Create A REST API

Run the following command to create a REST API:

composer create-project --prefer-dist Me-io/slim-api blog

Database connection

Out of the box slim-api supports MongoDB. So, to set up the connection with MongoDB create a new file bootstrap/ext.settings.php and configure the settings like this.

return [
	'mongodb' => [
	'uri'      => 'mongodb://localhost:27017',
	'database' => 'blog', // Collection name
	]
]

Creating a New Resource

Creating a new resource is very easy and straight-forward. Follow these simple steps to create a new resource. The complete structure for a resource is like this:

.
+-- app
|  +-- Post
|      +-- api_routes.php
|      +-- PostController.php
|      +-- PostModel.php  

Step 1: Create Route

To create route for a resource create a new folder inside app folder. Then inside that resource folder create a new route file named api_routes.php. For example lets create routes for Post reource.

$this->get('/posts', \App\Post\PostController::class . ":getAll");
$this->post('/posts', \App\Post\PostController::class . ":insertAndRetrieve");
$this->get('/posts/{id:[A-Z0-9a-z]+}', \App\Post\PostController::class . ":get");
$this->put('/posts/{id:[A-Z0-9a-z]+}', \App\Post\PostController::class . ":update");
$this->delete('/posts/{id:[A-Z0-9a-z]+}', \App\Post\PostController::class . ":delete");

For more info please visit Slim Routing page.

Step 2: Create Model

Create a model Post.php inside app/Post directory.

<?php

namespace App\Post;

use App\Base\Model\MongoDB;

class PostModel extends MongoDB
{
    /** 
    * @var string 
    */
    protected $collectionName = 'posts';
}

Visit Mongo PHP to learn about how to query mongodb using php.

Step 3: Create Controller

Create a controller PostController.php inside app/Post directory.

<?php

namespace App\Post;

use App\Base\Controller\RestController;

class PostController extends RestController
{
    protected $modelClass = PostModel::class;
}

Events

Slim API events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. To define your events for a Post resource lets create _events.php file inside app/Post.

<?php

$events = [
    'post.created' => function ($event, ...$params) {
        // Do processing of the event.
    }
];
return $events;

Now lets emmit post.created event by the following code.

<?php 

namespace App\Post;

use Slim\Http\Request;
use Slim\Http\Response;
use App\Base\Helper\Event;
use App\Base\Controller\RestController;

class PostController extends RestController
{
    protected $modelClass = PostModel::class;
	
	/**
     * @param Request $request
     * @param Response $response
     * @param $args
     * @return mixed
     * @throws \Exception
     */
	public function insert(Request $request, Response $response, $args) {
		// Create post and then retrieve it
		$post = [
		    "_id" 		  => "523b1153a2aa6a3233a91412",
		    "description" => "Buzzfeed asked a bunch of people...",
		    "title"       => "Cronut Mania: Buzzfeed asked a bunch of people...",
		];

		Event::emit('post.created', $post);
	}
}

Contributing

Anyone is welcome to contribute, however, if you decide to get involved, please take a moment to review the guidelines:

License

The code is available under the MIT license.

slim-api's People

Contributors

meabed avatar ziishaned avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.