2019年1月18日 星期五

簡易API設計

簡易API設計:

*建立controller
*設定API route
*查route
*migration
*model
*controller
*API測試工具:postman

========================
*建立controller:

php artisan make:controller api/CRUDController --resource

========================
*設定API route:

routes/api.php

Route::resource('crud', 'api\CRUDController')->except('create', 'edit');

========================
*查route:

php artisan route:list

+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+--------------+
| Domain | Method    | URI                    | Name             | Action                                                                 | Middleware   |
+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+--------------+
|        | GET|HEAD  | /                      |                  | App\Http\Controllers\ArticleController@index                           | web          |
|        | GET|HEAD  | api/crud               | crud.index       | App\Http\Controllers\api\CRUDController@index                          | api          |
|        | POST      | api/crud               | crud.store       | App\Http\Controllers\api\CRUDController@store                          | api          |
|        | GET|HEAD  | api/crud/{crud}        | crud.show        | App\Http\Controllers\api\CRUDController@show                           | api          |
|        | PUT|PATCH | api/crud/{crud}        | crud.update      | App\Http\Controllers\api\CRUDController@update                         | api          |
|        | DELETE    | api/crud/{crud}        | crud.destroy     | App\Http\Controllers\api\CRUDController@destroy                        | api          |
|        | GET|HEAD  | api/user               |                  | Closure                                                                | api,auth:api |
+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+--------------+

========================
*migration:

database\migrations\2019_01_05_033215_create_articles_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title',30);
            $table->text('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

========================
*model:

app\Article.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table='articles';

    protected $primaryKey='id';
   
    protected $fillable=['title','content'];
}

========================
*controller:

app\Http\Controllers\api\CRUDController.php

<?php

namespace App\Http\Controllers\api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Article;

class CRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts=Article::all();
        return response()->json(['status' => 'success', 'posts' => $posts]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $post=Article::create($request->all());
        return response()->json(['status' => 'success']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post=Article::find($id);

        if ($post) {
            return response()->json(['status' => 'success', 'post' => $post]);
        }

        return response()->json(['status' => 'error', 'message' => 'Id Not Found']);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $post=Article::findOrFail($id);
        $post2=$post->update($request->all());
       
        if ($post2) {
            return response()->json(['status' => 'success']);
        }

        return response()->json(['status' => 'error', 'message' => 'Post Not Found'], 404);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result=Article::destroy($id);

        if ($result) {
            return response()->json(['status' => 'success']);
        }

        return response()->json(['status' => 'error', 'message' => 'Post Not Found'], 404);
    }
}

========================
*API測試工具:postman

https://www.getpostman.com/



沒有留言:

張貼留言