Quick Rest API with Python for mock answers

I am testing a C # application that makes requests to another Restore API, and I want to make fun of the server. I knew basic python, and I was wondering if I could write a simple Rest API server without participating in large frameworks like Django. It would be a simple server, where I get json through the request body, and I need to return another json (with the return logic inside, like a view).

Yours faithfully!

Something simple:

@path(/api/v1/somepath, GET)
def my_function(request):
    json_input = request.body.json()

    # My logic here
    response.status = 200
    response.body = {'some_field': 'something'}
    return response
+6
source share
2 answers

If you really don't want to use external frameworks / libraries, you can create a simple class that extends BaseHTTPRequestHandler, something like this:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.data_string = self.rfile.read(int(self.headers['Content-Length']))

        self.send_response(200)
        self.end_headers()

        data = json.loads(self.data_string)
        # your processing
        outJson = {"success": True}
        self.wfile.write(json.dumps(outJson))

    def do_HEAD(self):
        self._set_headers()
        self.wfile.write("HEAD")

    def do_POST(self):
        self._set_headers()
        self.wfile.write("POST")

( 80):

def run(port=80):
    httpd = HTTPServer(('', port), S)
    print 'Starting httpd...'
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv
    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

, klein Flask microframeworks ( bottle), , klein :

import json
from klein import Klein

class ItemStore(object):
    app = Klein()

    def __init__(self):
        self._items = {}

    @app.route('/')
    def items(self, request):
        request.setHeader('Content-Type', 'application/json')
        return json.dumps(self._items)

    @app.route('/<string:name>', methods=['PUT'])
    def save_item(self, request, name):
        request.setHeader('Content-Type', 'application/json')
        body = json.loads(request.content.read())
        self._items[name] = body
        return json.dumps({'success': True})

    @app.route('/<string:name>', methods=['GET'])
    def get_item(self, request, name):
        request.setHeader('Content-Type', 'application/json')
        return json.dumps(self._items.get(name))

:

if __name__ == '__main__':
    store = ItemStore()
    store.app.run('localhost', 8080)

, mock apis , , , ngrok. .

+4

mountebank , . , .

0

All Articles