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ÔõôÑéÖ¤µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡