欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

restful api

程序员文章站 2024-03-25 19:26:22
...

到底什么是restful api?

举个例子,也是我碰到的第一个api列子

@openstack_api(url='/v2.1/{project_id}/servers/detail', method='GET', entry_point='nova')
def nova_get_user_resource_api(param, key_store, endpoint, code=0, response=None, e=None):
    return code, response, e

从名字上看就知道是个api了,先不管其他的,装饰器上的url和method是不是很眼熟,这就对了

所谓的restful api说得通俗点就是类似http协议一样的api风格,要详细了解的可以看看

阮一峰大神的文章点这里

结合http协议总结下就是

1.每一个URL代表一种资源
2.客户端和服务器之间,传递这种资源的某种表现层
3.客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层状态转化"。具体为:
GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源。 

 

这里我用的Flask实现一个简单的api,虽然工作一直是用的django,但是django写api还是比较繁琐的

from flask import Flask
app = Flask(__name__)

@app.route('/HelloWorld')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)

这样就在127.0.0.1:5000/HelloWorld下可以看到helloworld了

这里使用flask的router来定义api,同样是根据url+method的方法实现,这里需要注意的是post是修改操作,所以要把数据

先做序列化的处理

# -*- coding: utf-8 -*-

from flask import Flask, abort, request, jsonify

app = Flask(__name__)

asks = []

@app.route('/add_task/', methods=['POST'])
def add_task():
    if not request.json or 'id' not in request.json or 'info' not in request.json: abort(400)
    task = { 'id': request.json['id'], 'info': request.json['info'] }
    tasks.append(task)
    return jsonify({'result': 'success'})

@app.route('/get_task/', methods=['GET'])
def get_task():
    if not request.args or 'id' not in request.args:
        return jsonify(tasks)
    else:
        task_id = request.args['id']
        task = filter(lambda t: t['id'] == int(task_id), tasks)
        return jsonify(task) if task else jsonify({'result': 'not found'})


if __name__ == "__main__":
    app.run(debug=True)

有兴趣的可以研究下router的内部

    def route(self, rule, **options):
        """A decorator that is used to register a view function for a
        given URL rule.  This does the same thing as :meth:`add_url_rule`
        but is intended for decorator usage::

            @app.route('/')
            def index():
                return 'Hello World'

        For more information refer to :ref:`url-route-registrations`.

        :param rule: the URL rule as string
        :param endpoint: the endpoint for the registered URL rule.  Flask
                         itself assumes the name of the view function as
                         endpoint
        :param options: the options to be forwarded to the underlying
                        :class:`~werkzeug.routing.Rule` object.  A change
                        to Werkzeug is handling of method options.  methods
                        is a list of methods this rule should be limited
                        to (``GET``, ``POST`` etc.).  By default a rule
                        just listens for ``GET`` (and implicitly ``HEAD``).
                        Starting with Flask 0.6, ``OPTIONS`` is implicitly
                        added and handled by the standard request handling.
        """
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator