🗣 Wd提问: thinkphp api
🤖 Ai回答: Sure! Here's a comprehensive guide on how to build a RESTful API using ThinkPHP (specifically ThinkPHP 6.x, the latest stable version as of 2024).
✅ ThinkPHP API Development Guide (ThinkPHP 6)
1、✅ Install ThinkPHP 6
If you haven't installed ThinkPHP yet, use Composer:
bash
composer create-project topthink/think myapi
cd myapi
This creates a new ThinkPHP 6 project in the `myapi` folder.
2、✅ Project Structure Overview (API-Focused)
ThinkPHP 6 follows MVC pattern、For APIs, we’ll focus on:
app/
├── controller/ API Controllers
├── model/ Database Models
├── validate/ Request Validation
├── service/ (Optional) Business Logic Layer
└── ..、
We’ll create a simple User API with `GET /api/users`, `POST /api/users`, etc.
3、✅ Configure Routing (routes/route.php)
Edit `routes/route.php` to define API routes:
php
<?php
use think\facade\Route;
// API prefix
Route::group('api', function () {
Route::get('users', 'api/User/index'); // GET /api/users
Route::post('users', 'api/User/store'); // POST /api/users
Route::get('users/:id', 'api/User/show'); // GET /api/users/1
Route::put('users/:id', 'api/User/update'); // PUT /api/users/1
Route::delete('users/:id', 'api/User/delete'); // DELETE /api/users/1
});
💡 Tip: Use `api/` prefix for clear separation of API endpoints.
4、✅ Create Controller (app/controller/api/User.php)
Create the controller:
bash
php think make:controller api/User
Edit `app/controller/api/User.php`:
php
<?php
namespace app\controller\api;
use app\BaseController;
use app\model\User;
use think\Request;
use think\facade\Validator;
class User extends BaseController
{
// GET /api/users
public function index()
{
$users = User::all();
return json([
'code' = 200,
'msg' = 'Success',
'data' = $users
]);
}
// POST /api/users
public function store(Request $request)
{
$data = $request-post();
// Validate input
$validate = validate('User');
if (!$validate-check($data)) {
return json([
'code' = 400,
'msg' = $validate-getError(),
'data' = []
], 400);
}
$user = User::create($data);
return json([
'code' = 201,
'msg' = 'User created',
'data' = $user
], 201);
}
// GET /api/users/:id
public function show($id)
{
$user = User::find($id);
if (!$user) {
return json(['code' = 404, 'msg' = 'User not found'], 404);
}
return json(['code' = 200, 'msg' = 'Success', 'data' = $user]);
}
// PUT /api/users/:id
public function update(Request $request, $id)
{
$user = User::find($id);
if (!$user) {
return json(['code' = 404, 'msg' = 'User not found'], 404);
}
$data = $request-put();
$validate = validate('User');
if (!$validate-check($data)) {
return json(['code' = 400, 'msg' = $validate-getError()], 400);
}
$user-save($data);
return json(['code' = 200, 'msg' = 'Updated', 'data' = $user]);
}
// DELETE /api/users/:id
public function delete($id)
{
$user = User::find($id);
if (!$user) {
return json(['code' = 404, 'msg' = 'User not found'], 404);
}
$user-delete();
return json(['code' = 200, 'msg' = 'Deleted']);
}
}
5、✅ Create Model (app/model/User.php)
bash
php think make:model User
Edit `app/model/User.php`:
php
<?php
namespace app\model;
use think\Model;
class User extends Model
{
protected $table = 'users';
protected $pk = 'id';
protected $visible = ['id', 'name', 'email', 'created_at']; // Hide password, etc.
// Define fillable fields for mass assignment
protected $allowField = ['name', 'email', 'password'];
}
💡 Use `protected $visible` to control JSON output fields.
6、✅ Create Validation Rule (app/validate/User.php)
bash
php think make:validate User
Edit `app/validate/User.php`:
php
<?php
namespace app\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name' = 'require|max:50',
'email' = 'require|email|unique:user,email',
'password' = 'require|min:6',
];
protected $message = [
'name.require' = 'Name is required',
'name.max' = 'Name cannot exceed 50 characters',
'email.require'= 'Email is required',
'email.email' = 'Invalid email format',
'email.unique' = 'Email already exists',
'password.require' = 'Password is required',
'password.min' = 'Password must be at least 6 characters',
];
protected $scene = [
'create' = ['name', 'email', 'password'],
'update' = ['name', 'email'], // password optional on update
];
}
💡 Use scenes for different validation contexts (e.g., create vs update).
In controller, use:
php
$validate = validate('User')-scene('update');
7、✅ Database Migration (Create users table)
Run migration:
bash
php think make:migration create_users_table
Edit the generated migration file (`database/migration/xxx_create_users_table.php`):
php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table-id();
$table-string('name', 50);
$table-string('email', 100)-unique();
$table-string('password', 255);
$table-timestamps();
});
}
Run migration:
bash
php think migrate
8、✅ Test Your API
Start the built-in server:
bash
php think run
Then test with `curl` or Postman:
✅ GET all users:
bash
curl http://127.0.0.1:8000/api/users
✅ POST new user:
bash
curl -X POST http://127.0.0.1:8000/api/users \
-H Content-Type: application/json \
-d '{name:John Doe,email:john@65.hk,password:123456}'
✅ GET single user:
bash
curl http://127.0.0.1:8000/api/users/1
9、✅ Optional: API Response Helper
Create a helper trait to standardize responses:
app/trait/ApiResult.php
php
<?php
namespace app\trait;
trait ApiResult
{
public function success($data = [], $msg = 'Success', $code = 200)
{
return json([
'code' = $code,
'msg' = $msg,
'data' = $data
], $code);
}
public function error($msg = 'Error', $code = 400)
{
return json([
'code' = $code,
'msg' = $msg,
'data' = []
], $code);
}
}
Use in controller:
php
use app\trait\ApiResult;
class User extends BaseController
{
use ApiResult;
public function index()
{
return $this-success(User::all());
}
}
10、✅ Security & Best Practices
| Best Practice | Description |
| ✅ Use HTTPS | Always in production |
| ✅ Token Auth | Use JWT or ThinkPHP’s built-in session/token |
| ✅ Rate Limiting | Use middleware like `think\middleware\RateLimit` |
| ✅ Input Sanitization | Always validate + sanitize inputs |
| ✅ Hide Sensitive
📣 商家广告 :
👍
0
👎
IP地址: 39.159.170.117
搜索次数: 61
提问时间: 2025-11-08 09:33:02
🛒 域名购买 :
uq.gs 03.gold yw.gs i-f.com.cn 0.bj.cn 61.gold kou.red 279.net.cn sjtp.cn lf.gs
❓️ 热门提问 :
可以自动挂机的网络游戏 Swift源码开发 免费cdn服务器 可以挂机网页游戏 云空间有用吗? 买个云主机 xss主机 工信部云计算证书 17域名 虚拟内存占用的是什么空间 豌豆Ai站群搜索引擎系统
🌐 域名评估 :
yu8.ah.cn vivo.mo.cn w.hb.cn d.nx.cn g.ah.cn gz.gs mdfai.com dd.mo.cn oppo.tw.cn mu.cx
⛏ 最新挖掘 :
凯里酸汤鱼 贵阳烤脑花 都匀毛尖茶 花溪牛肉粉 贵阳烤生蚝 贵阳烤豆腐 贵阳纸包鱼 贵阳特色菜
🖌 热门作画 :
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊 :
🔗 友情链接 :
站群出租
网站排名优化培训
ai提问
🧰 站长工具 :Ai工具 whois查询 搜索
📢 温馨提示 :本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持 :本站由豌豆Ai 提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。