
api是应用程序编程接口,可以理解为与不同软件系统进行通信的通道。它本质上是一个预定义的函数。
api有多种形式,最流行的一种是使用http协议提供服务(如:restful),只要符合规定就可以正常使用。现在很多企业都使用第三方提供的api,也为第三方提供api,所以api的设计也需要谨慎。
阐明功能
在设计之初,你需要按照业务功能点或者模块来组织api的功能,明确你的api需要提供的
清晰的代码逻辑
保持代码整洁并添加必要的注释以确保界面具有单一功能。如果接口需要复杂的业务逻辑,建议将其拆分为多个接口,或者将功能独立封装成公共方法,避免接口中代码过多,不利于维护和后期迭代。
必要的安全校验和
常见的解决方案是使用数字签名。为每个http请求添加签名,服务器端验证签名的有效性,保证请求的真实性。
记录
日志记录对于及时定位问题至关重要。
最小化耦合
一个好的 api 应该尽可能简单。如果api之间的业务耦合度太高,很容易导致某段代码出现异常,导致相关api不可用。所以还是尽量避免api之间关系的复杂性吧。
返回有意义的状态代码
api返回数据中应携带状态码数据。例如,200表示请求正常,500表示服务器出现内部错误。返回通用的状态码有利于问题定位。
开发文档
由于api是提供给第三方或者内部使用的,所以开发文档是必不可少的,否则别人不知道如何使用。
一个好的api开发文档应该包含以下元素:
如果对开发环境满意,大概不到10分钟,就可以完成一个简单api接口的开发(只是一个demo)。
开发前需要安装jdk、maven和ide。
创建一个基于spring boot的新项目。为了快速完成,我选择使用(start.spring.io)来生成我的项目。通过【搜索要添加的依赖项】可以选择包。我只导入了spring mvc,如果需要通过mybatis访问数据库,也可以选择这里,然后点击生成项目。
解压下载的项目并将其引入到您的ide中,然后创建一个新类:com.wukong.apidemo.controller.apicontroller。
在这个类中添加一个方法,主要使用@restcontroller、@requestmapping、@responsebody标签。
最简单的api接口已经完成。我们可以启动项目,访问对应的接口地址,并获取接口返回信息。
我们可以使用swagger来帮助我们生成接口文档,优化api接口。
python flask 和 java spring boot 都可以用来高效创建 api 接口。
spring boot 将开发过程简化为简单。对于python,我推荐一个用于开发api接口的第三方包:fastapi。
这是一个快速高效的工具,具有以下功能:
构建 restful api 似乎是开发人员的工作,事实上,有很多场景需要测试开发人员构建 restful api。
有些测试人员会构建restful api,将服务器端域名劫持到自己的api上,故意返回各种异常,以查看客户端的稳定性。
如果您是新用户,请直接将本程序的所有文件上传在任一文件夹下,Rewrite 目录下放置了伪静态规则和筛选器,可将规则添加进IIS,即可正常使用,不用进行任何设置;(可修改图片等)默认的管理员用户名、密码和验证码都是:yeesen系统默认关闭,请上传后登陆后台点击“核心管理”里操作如下:进入“配置管理”中的&ld
0
rest: representational state transfer get - /api/category - retrieve all categories post - /api/category - add a new category put - /api/category - update a category delete - /api/category - delete a category get - /api/comment - retrieve all the stored comments post - /api/comment - add new comment
要求:python3.*,postgresql.
project/ ├── app.py ├── config.py ├── migrate.py ├── model.py ├── requirements.txt ├── resources │ └── hello.py │ └── comment.py │ └── category.py └── run.py
requirements.txt如下:
flask - python 微框架
flask_restful - flask 的扩展,用于快速构建 rest api。
flask_script - 提供在 flask 中编写外部脚本的支持。
flask_migrate - 使用 alembic 的 flask 应用程序进行 sqlalchemy 数据库迁移。
marshmallow - 用于复杂数据类型和 python 数据类型转换。
flask_sqlalchemy - 添加了对 sqlalchemy 的支持的 flask 扩展。
flask_marshmallow - 烧瓶和棉花糖之间的中间层。
marshmallow-sqlalchemy - sqlalchemy 和 marshmallow 之间的中间层。
psycopg - 用于 python 的 postgresql api。
安装依赖项
# pip3 install -r requirements.txt
安装并配置postgresql(以ubuntu 16.04为例)
# sudo apt-get update && sudo apt-get upgrade # apt-get install postgresql postgresql-contrib # su - postgres $ createdb api $ createuser andrew --pwprompt #create user $ psql -d api -c "alter user andrew with password 'api';"
配置
from flask import blueprint
from flask_restful import api
from resources.hello import hello
from resources.category import categoryresource
from resources.comment import commentresource
api_bp = blueprint('api', __name__)
api = api(api_bp)
# routes
api.add_resource(hello, '/hello')
api.add_resource(categoryresource, '/category')
api.add_resource(commentresource, '/comment')
快速入门
app.py
from flask import blueprint
from flask_restful import api
from resources.hello import hello
api_bp = blueprint('api', __name__)
api = api(api_bp)
# route
api.add_resource(hello, '/hello')
资源/hello.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author: xurongzhong#126.com wechat:pythontesting qq:37391319
# createdate: 2018-1-10
from flask_restful import resource
class hello(resource):
def get(self):
return {"message": "hello, world!"}
def post(self):
return {"message": "hello, world!"}
run.py
from flask import flask
def create_app(config_filename):
app = flask(__name__)
app.config.from_object(config_filename)
from app import api_bp
app.register_blueprint(api_bp, url_prefix='/api')
return app
if __name__ == "__main__":
app = create_app("config")
app.run(debug=true)
开始服务
$ python3 run.py * running on http://127.0.0.1:5000/ (press ctrl+c to quit) * restarting with stat * debugger is active! * debugger pin: 136-695-873
使用浏览器访问:http://127.0.0.1:5000/api/hello
{
"hello": "world"
}
访问数据库
from flask import flask
from marshmallow import schema, fields, pre_load, validate
from flask_marshmallow import marshmallow
from flask_sqlalchemy import sqlalchemy
ma = marshmallow()
db = sqlalchemy()
class comment(db.model):
__tablename__ = 'comments'
id = db.column(db.integer, primary_key=true)
comment = db.column(db.string(250), nullable=false)
creation_date = db.column(db.timestamp, server_default=db.func.current_timestamp(), nullable=false)
category_id = db.column(db.integer, db.foreignkey('categories.id', ondelete='cascade'), nullable=false)
category = db.relationship('category', backref=db.backref('comments', lazy='dynamic' ))
def __init__(self, comment, category_id):
self.comment = comment
self.category_id = category_id
class category(db.model):
__tablename__ = 'categories'
id = db.column(db.integer, primary_key=true)
name = db.column(db.string(150), unique=true, nullable=false)
def __init__(self, name):
self.name = name
class categoryschema(ma.schema):
id = fields.integer()
name = fields.string(required=true)
class commentschema(ma.schema):
id = fields.integer(dump_only=true)
category_id = fields.integer(required=true)
comment = fields.string(required=true, validate=validate.length(1))
creation_date = fields.datetime()
迁移.py
from flask_script import manager
from flask_migrate import migrate, migratecommand
from model import db
from run import create_app
app = create_app('config')
migrate = migrate(app, db)
manager = manager(app)
manager.add_command('db', migratecommand)
if __name__ == '__main__':
manager.run()
数据迁移
$ python3 migrate.py db init $ python3 migrate.py db migrate $ python migrate.py db upgrade
测试
您可以使用curl,例如:
curl http://127.0.0.1:5000/api/Category --data '{"name":"test5","id":5}' -H "Content-Type: application/json"
以上就是如何制作API接口?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号