Search This Blog

Wednesday, March 14, 2018

Build a Simple Python Based REST API

As a developer or a tester or as a hobby you might need to create simple API. So I think below code will be helpful to complete the task.

Here I have used python + flask to create the API

Before proceed you need python installed machine with flask and flask-httpauth.

Use "python -m pip install ......." to install necessary components.

You can use following code for develop a simple API and do further.


Here, you can change the port by changing the port in "app.run(debug = True, host='0.0.0.0', port=9090)" section.

Open a notepad copy past the code, and save it with <desire_name>.py


Let me know if you have encounter with any errors.

#!flask/bin/python
__author__ = "Sasadara"

import os
from flask import Flask, jsonify, abort, request, make_response, url_for
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__, static_url_path = "")
auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
    if username == 'sasadara':
        return 'py'
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify( { 'error': 'Unauthorized access' } ), 403)
    # return 403 instead of 401 to prevent browsers from displaying the default auth dialog
   
@app.errorhandler(400)
def not_found(error):
    return make_response(jsonify( { 'error': 'Bad request' } ), 400)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify( { 'error': 'Not found' } ), 404)


@app.route("/")
def hello():
    return "Hello World!"

@app.route("/api/file", methods = ['GET'])
@auth.login_required
def openfile():
 
    file = os.system('bat.bat')
    return "Done"

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown', methods=['GET'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

   
if __name__ == '__main__':
    app.run(debug = True, host='0.0.0.0', port=9090)

Hope this will help.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *