laravelдapiÔõôÑéÖ¤
Ëæ×Åweb apiµÄÆÕ¼°£¬apiµÄÇå¾²ÐÔ±äµÃÔ½À´Ô½Ö÷Òª¡£ÔÚlaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÄÚÖõÄÑéÖ¤¹æÔòºÍÖÐÑë¼þÀ´¶ÔapiÇëÇó¾ÙÐÐÑéÖ¤ºÍ±£»¤¡£
ʹÓÃLaravelÄÚÖõÄÑéÖ¤¹æÔò
LaravelÌṩÁËһϵÁеÄÑéÖ¤¹æÔò£¬Èç¡°required¡±£¨±ØÌîÏ¡¢¡°email¡±£¨ÓÊÏäÃûÌ㩵ȵȡ£ÎÒÃÇ¿ÉÒÔ½«ÕâЩ¹æÔòÓ¦Óõ½ÎÒÃǵÄAPI½Ó¿ÚÖУ¬´Ó¶ø°ü¹Ü½Ó¿Ú²ÎÊýµÄ׼ȷÐÔ¡£
ÀýÈ磬ÎÒÃÇÏëÒªÑéÖ¤Ò»¸ö×¢²áAPI½Ó¿ÚµÄ²ÎÊý£¬¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
public function register(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8', ]); // ¶ÔÇëÇó²ÎÊý¾ÙÐд¦Àí // ... // ×¢²áÓû§ // ... }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃÁË$request->validate()ÒªÁìÀ´¶ÔÇëÇó²ÎÊý¾ÙÐÐÑéÖ¤¡£ÈôÊÇÑé֤ʧ°Ü£¬Laravel»á×Ô¶¯Å׳öÒ»¸öValidationExceptionÒì³££¬Ö®ºóÎÒÃÇÐèÒªÔÚÒì³£´¦ÀíÆ÷Öд¦ÀíÕâ¸öÒì³£¡£
ʹÓÃLaravelÄÚÖõÄÖÐÑë¼þ
Laravel»¹ÌṩÁËÐí¶àÖÐÑë¼þÀ´ÔöÇ¿APIµÄÇå¾²ÐÔ¡£ÒÔÏÂÊÇһЩ³£ÓõÄÖÐÑë¼þ£º
auth£ºÓÃÓÚÓû§ÈÏÖ¤£¬Ö»ÔÊÐíÒѵÇÈÎÃü»§»á¼û½Ó¿Ú£»
throttle£ºÓÃÓÚÏÞÖÆAPI½Ó¿ÚµÄÇëÇóƵÂÊ£¬×èÖ¹±»¹¥»÷»òÀÄÓã»
cors£ºÓÃÓÚ¿çÓò×ÊÔ´¹²Ïí£¬ÔÊÐí¿çÓòÇëÇó£»
csrf£ºÓÃÓÚ±ÜÃâ¿çÕ¾ÇëÇóαÔì¹¥»÷£»
ÎÒÃÇ¿ÉÒÔÖ±½ÓÔÚ·Óɽç˵ÖÐʹÓÃÕâЩÖÐÑë¼þ£¬ÈçÏÂËùʾ£º
// ½ç˵ÐèÒªÈÏÖ¤µÄAPI½Ó¿Ú Route::middleware(['auth'])->group(function () { Route::post('/api/foo', 'FooController@create'); Route::put('/api/foo/{id}', 'FooController@update'); }); // ½ç˵ÔÊÐí¿çÓò»á¼ûµÄAPI½Ó¿Ú Route::middleware(['cors'])->group(function () { Route::get('/api/bar', 'BarController@index'); }); // ½ç˵ÏÞÖÆÇëÇóƵÂʵÄAPI½Ó¿Ú Route::middleware(['throttle'])->group(function () { Route::get('/api/baz', 'BazController@index'); });
µÇ¼ºó¸´ÖÆ
×Ô½ç˵ÖÐÑë¼þ
³ýÁËʹÓÃLaravelÄÚÖõÄÖÐÑë¼þÖ®Í⣬ÎÒÃÇ»¹¿ÉÒÔ×Ô½ç˵ÖÐÑë¼þÀ´ÊµÏÖ¸üÖØ´óµÄÑéÖ¤Âß¼¡£
ÀýÈ磬ÎÒÃÇÏëÒªÑéÖ¤APIÇëÇóÖдøÓÐÁîÅÆ£¨token£©²ÎÊý£¬²¢ÇÒÕâ¸öÁîÅÆÊÇÓÐÓõģ¬¾Í¿ÉÒÔ½¨ÉèÒ»¸ö×Ô½ç˵ÖÐÑë¼þÀ´ÊµÏÖÕâ¸ö¹¦Ð§£º
php artisan make:middleware ValidateToken
µÇ¼ºó¸´ÖÆ
public function handle($request, Closure $next) { $token = $request->input('token'); if (! $token || ! Token::isValid($token)) { return response()->json([ 'status' => 'error', 'message' => 'Invalid token provided', ], 401); } return $next($request); }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈ»ñÈ¡ÁËÇëÇóÖеġ°token¡±²ÎÊý£¬²¢ÇÒ¼ì²éÁËÕâ¸öÁîÅÆÊÇ·ñÓÐÓá£ÈôÊÇÎÞЧ£¬¾Í·µ»Ø401״̬ÂëºÍ¹ýʧÐÅÏ¢¡£²»È»£¬¾Í¼ÌÐø´¦ÀíÕâ¸öÇëÇó¡£
×îºó£¬ÎÒÃÇ¿ÉÒÔÔÚ·Óɽç˵ÖÐʹÓÃÕâ¸ö×Ô½ç˵ÖÐÑë¼þ£º
Route::middleware(['validate_token'])->group(function () { Route::post('/api/qux', 'QuxController@create'); });
µÇ¼ºó¸´ÖÆ
×ܽá
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÄÚÖõÄÑéÖ¤¹æÔò¡¢ÖÐÑë¼þºÍ×Ô½ç˵ÖÐÑë¼þÀ´ÑéÖ¤APIÇëÇó£¬ÔöÇ¿APIµÄÇå¾²ÐÔ¡£Í¬Ê±£¬ÎÒÃÇÒ²¿ÉÒÔƾ֤ÏêϸµÄÓªÒµÐèÇó£¬ÊµÏÖ¸üÖØ´óµÄÑéÖ¤Âß¼£¬±£»¤API½Ó¿Ú²»±»ÀÄÓûò¹¥»÷¡£
ÒÔÉϾÍÊÇlaravelдapiÔõôÑéÖ¤µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡