# See the License for the specific language governing permissions and # limitations under the License. """Exposes all of the resource endpoints mounted in Flask-Blueprint style. Uses restplus namespaces to mount individual api endpoints into the service. All services have 2 defaults sets of endpoints: - ops - metaTEMPLATE_FOLDER_PATH = None That are used to expose operational health information about the service, and meta information. """ from flask_restx import Api from .meta import api as META_API from .ops import api as OPS_API from .feedback import api as FEEDBACK_API # This will add the Authorize button to the swagger docs # TODO oauth2 & openid may not yet be supported by restplus <- check on this API = Api( title='Feedback API', version='1.0', description='Feedback API for Service BC', prefix='/api/v1') API.add_namespace(OPS_API, path='') API.add_namespace(META_API, path='') API.add_namespace(FEEDBACK_API, path='')
api = Api(app, version='1.0', title='Data service API', description="""API for QWC Data service. ## General Information for all operations ### Datatypes-Encoding JSON only defines recommendations or has no information concerning the encoding of some quite common used database data types. Following a description on how these are encoded in the data service API. - Date: ISO date strings `YYYY-MM-DD` - Datetime: ISO date/time strings `YYYY-MM-DDThh:mm:ss` - UUID: Hex-encoded string format. Example: `'6fa459ea-ee8a-3ca4-894e-db77e160355e'` ### Feature-ID For operations like updating or deleting features, records are identified by a feature `id`. This `id` refers to the primary key of the database table and is usually kept constant over time. ## Filter expressions Query operations support passing filter expressions to narrow down the results. This expression is a serialized JSON array of the format: [["<name>", "<op>", <value>],"and|or",["<name>","<op>",<value>],...] * `name` is the attribute column name * `op` can be one of "=", "!=", "<>", "<", ">", "<=", ">=", "LIKE", "ILIKE", "IS", "IS NOT" The operators are applied on the original database types. If value is `null`, the operator should be `IS` or `IS NOT`. * `value` can be of type `string`, `int`, `float` or `null`. For string operations, the SQL wildcard character `%` can be used. ### Filter examples * Find all features in the dataset with a number field smaller 10 and a matching name field: `[["name","LIKE","example%"],"and",["number","<",10]]` * Find all features in the dataset with a last change before 1st of January 2020 or having `NULL` as lastchange value: `[["lastchange","<","2020-01-01T12:00:00"],"or",["lastchange","IS",null]]` """, default_label='Data edit operations', doc='/api/')
from flask import Flask, request, send_from_directory, abort, Response from flask_restx import Resource, Api import eventlet eventlet.monkey_patch() from pyinfraboxutils import get_logger logger = get_logger('api') storage_path = '/tmp/collector/' app = Flask(__name__) app.config['OPA_ENABLED'] = False api = Api(app) @api.route('/ping') class Ping(Resource): def get(self): return {'status': 200} def handle_entry(entry): if 'kubernetes' not in entry: return e = entry['kubernetes'] pod_path = os.path.join(storage_path, e['pod_id']) if not os.path.exists(pod_path): os.makedirs(pod_path)
# app/__init__.py from flask_restx import Api from flask import Blueprint from .main.controller.user_controller import api as user_ns from .main.controller.auth_controller import api as auth_ns blueprint = Blueprint('api', __name__) api = Api(blueprint, title='FLASK RESTPLUS(RESTX) API BOILER-PLATE WITH JWT', version='1.0', description='a boilerplate for flask restplus (restx) web service') api.add_namespace(user_ns, path='/user') api.add_namespace(auth_ns)
authorizations = { 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' }, } diretorio = Path('.') dt_release = datetime.fromtimestamp(diretorio.stat().st_mtime) api = Api( blueprint, title='OZOMALI API RESTFULL', # WITH JWT AUTH', version='2.0', description='By Ozomali development team | last update: ' + dt_release.strftime("%d/%m/%Y, %H:%M:%S"), security='apiKey', authorizations=authorizations) api.add_namespace(auth_ns, path='/auth') api.add_namespace(usuario_ns, path='/usuarios') api.add_namespace(perfil_ns, path='/perfis') api.add_namespace(fornecedor_ns, path='/fornecedores') api.add_namespace(contato_ns, path='/contatos') api.add_namespace(tipocontato_ns, path='/tipocontatos') api.add_namespace(produto_ns, path='/produtos') api.add_namespace(movimentacao_ns, path='/movimentacoes') api.add_namespace(preco_ns, path='/precos') # TODO AUTH JWT
from JobTracker.utils.colourisation import printColoured from JobTracker.utils.debug import pretty_print_dict from JobTracker.exceptions import InvalidUserInput from flask_restx import Resource, Api, fields from careerjet_api import CareerjetAPIClient import requests import json from fake_useragent import UserAgent # Blueprint definitions jobs_router = Blueprint("jobs", __name__) jobs_api = Api( jobs_router, doc="/doc", title="Job Post Search", description="Routes for retrieving job postings", default="/api/jobs", default_label="Job Post Search Namespace", ) def get_suggestions(query): keyword = query keyword.replace(" ", "+") url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + keyword ua = UserAgent() headers = {} headers = {"user-agent": ua.chrome} response = requests.get(url, headers=headers, verify=False)
from flask import Blueprint, request from flask_restx import Api, Resource, fields from project import db from project.api.models import User users_blueprint = Blueprint("users", __name__) api = Api(users_blueprint) # wrapper around SQLAlchemy model to enable payload validation user = api.model( "User", { "id": fields.Integer(readOnly=True), "username": fields.String(required=True), "email": fields.String(required=True), "created_date": fields.DateTime, }, ) class UsersList(Resource): # validate param allows validation and throws error otherwise @api.expect(user, validate=True) def post(self): post_data = request.get_json() username = post_data.get("username") email = post_data.get("email") response_object = {}
from flask_restx import Api from flask import Blueprint from .user.controller import api as user_ns from .project.controller import api as project_ns from .post.controller import api as post_ns from .feed.controller import api as feed_ns # Import controller APIs as namespaces. api_bp = Blueprint("api", __name__) api = Api(api_bp, title="API", description="Main routes.") # API namespaces api.add_namespace(user_ns) api.add_namespace(project_ns) api.add_namespace(post_ns) api.add_namespace(feed_ns)
import os from distutils.util import strtobool from flask import current_app from flask_restx import Api import sqlalchemy.orm.exc from ..logging import exception_as_rfc5424_structured_data api = Api( version='1.0', title='Catalogue service', description='A catalogue service implemented with a Flask RESTX powered API' ) debug = strtobool(os.environ.get('FLASK_DEBUG', 'False')) @api.errorhandler def default_error_handler(e): current_app.logger.error('An unhandled exception occurred: %s', e, extra=exception_as_rfc5424_structured_data(e)) if not debug: return {'message': 'An unexpected error occurred'}, 500 @api.errorhandler(sqlalchemy.orm.exc.NoResultFound) def database_not_found_error_handler(e): current_app.logger.warning( "A database item was expected but was not found: %s", e) return {'message': 'A result was required but none was found.'}, 404
from flask import Flask, request from flask_restx import Api, Resource, fields import pigpio, time status = None pi = pigpio.pi() app = Flask(__name__) api = Api( app, version="1.0", title="LightSwitcher API Document", description= "LightSwitcher is an API server that controls DC serbo motors connected to a RaspberryPi", doc="/doc/", default="Default Endpoint", default_label="default") response_model = api.model( "LightSwitcherResponse", {"status": fields.String(description="Status of light")}) expect_model = api.model( "LightSwitcherExpect", {"param": fields.String(description="Parameter for switching light")}) @api.route("/") @api.expect(expect_model) class Switch(Resource): @api.marshal_with(response_model)
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import str from future import standard_library standard_library.install_aliases() from flask import Blueprint from flask_restx import Api, apidoc, Namespace from .specs import hysds_io_ns services = Blueprint('api_v0-2', __name__, url_prefix='/api/v0.2') api = Api(services, ui=False, version="0.2", title="GRQ API", description="API for GRQ Services.") NAMESPACE = "grq" grq_ns = Namespace(NAMESPACE, description="GRQ operations") api.add_namespace(grq_ns) api.add_namespace(hysds_io_ns) @services.route('/doc/', endpoint='api_doc') def swagger_ui(): return apidoc.ui_for(api)
} } } # authorizations = { # 'apikey': { # 'type': 'apiKey', # 'in': 'header', # 'name': 'X-API-KEY' # } # } api = Api( app=app, version="1.0", title="Flask Api", description="Flask Api PostgreSQL", # security='apikey', security=[{ 'oauth2': ['read', 'write'] }], authorizations=authorizations) name_space1 = api.namespace('Authentication', description='Authentication') name_space2 = api.namespace('Actors CRUD', description='Actors CRUD Description') name_space3 = api.namespace('Movies CRUD', description='Movies CRUD Description') name_space4 = api.namespace( 'Actor Movie Relations CRUD', description='Actor Movie Relations CRUD Description')
from flask import Blueprint from flask_restx import Api, Resource from flask_restx.namespace import Namespace ping_blueprint = Blueprint("ping", __name__) api = Api(ping_blueprint) ping_namespace = Namespace("ping") class Ping(Resource): def get(self): return { "status": "success!", "message": "pong", } ping_namespace.add_resource(Ping, "")
restaurant_bp = Blueprint("restaurant_bp",__name__) authorizations = { 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'authorization' } } restaurant_api = Api(restaurant_bp, default='Restaurant', default_label='This is the Restaurant Api service', version='0.0.1', title='Restaurant API with Python', description="Restaurant Table Booking and Payment", ordered=False, authorizations=authorizations, security='apikey', ) restaurant_namespace = restaurant_api.namespace('restaurants') from .restaurant_views import Show_Restaurants,Book_Table,OrderHistory,Bill,Show_Tables,CancelBooking,CheckIn,\ CreateRestaurant,CreateTableTypes,Table_Rest_Mapping restaurant_namespace.add_resource(Show_Restaurants,"/allRestaurants") restaurant_namespace.add_resource(Show_Tables,"/showTables/<string:restaurant_name>") restaurant_namespace.add_resource(Book_Table,"/bookTable") restaurant_namespace.add_resource(OrderHistory,"/orderHistory") restaurant_namespace.add_resource(Bill,"/bill")
# coding: utf-8 from flask import Flask, render_template from flask_restx import Resource, Api, fields, reqparse import requests, json import pymysql import datetime # Config Flask App Definition app = Flask(__name__) api = Api(app=app, version="0.1", doc="/api", title="Mon API", description="ceci est une description de l'api de test", default="mon api", default_label='ceci est une api de test', validate=True) db_host = "localhost" db = pymysql.connect(host=db_host, user="******", passwd="toor", db="station_meteo") @api.route("/print_data") class PrintData(Resource): def get(self): sql_query = " select id, temperature, humidity, DATE_FORMAT(date, '%Y-%m-%d %T') as date, id_sonde from data;" cursor = db.cursor(pymysql.cursors.DictCursor)
import json import requests from flask import Flask from flask_restx import Api, Resource flask_app = Flask(__name__) flask_api = Api( flask_app, version='1.0', title='User Distance API', description= 'API that calls the bpdts-test-app API and returns users listed in a city and, optionally, within a given distance from a city - 50 miles from London by default' ) api_namespace = flask_api.namespace("user_distances") import resources.routes
from flask import Flask, render_template, request import flask.scaffold flask.helpers._endpoint_from_view_func = flask.scaffold._endpoint_from_view_func from flask_restx import Resource, Api from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_migrate import Migrate from flask_jwt_extended import JWTManager from monopoly.middleware import Middleware from flask_cors import CORS, cross_origin from flask_session import Session db = SQLAlchemy() migrate = Migrate() ma = Marshmallow() flask_api = Api() jwt = JWTManager() session = Session() def create_app(): app = Flask(__name__, template_folder="static") if app.config["ENV"] == "production": app.config.from_object('config.ProductionConfig') else: app.config.from_object('config.DevelopmentConfig') db.init_app(app) migrate.init_app(app, db) ma.init_app(app)
import os from flask import Blueprint, Flask, abort, session, request, redirect from flask_wtf.csrf import CSRFProtect from flask_restx import Resource, Api, fields from flask.json import jsonify app = Flask(__name__, template_folder="../public", static_folder="../public", static_url_path='') app.config['ERROR_404_HELP'] = False # csrf = CSRFProtect(app) blueprint = Blueprint('api', __name__, url_prefix='/v1') api = Api(blueprint, title="My API", version='v0.1', description='Description') app.register_blueprint(blueprint) from server.routes import * # noqa @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') return response
from flask import Flask from config import Config from flask_mongoengine import MongoEngine from flask_restx import Api, api from werkzeug.utils import * #from functools import cached_property api = Api() app = Flask(__name__) app.config.from_object(Config) db = MongoEngine() db.init_app(app) api.init_app(app) from application import routes
from werkzeug.datastructures import FileStorage from _logging._logger import get_logger from data_base.mongo_wrapper import MongoWrapper from nats_wrapper.nats_wrapper import send_message from visualization.vizualization import plot logger = get_logger(__name__) def prepare_response(message: json, status: int): logger.info(f"Response:{message}") return message, status api = Api(title='Deep learning API', default="DeepLearning") app = Flask(__name__) api.init_app(app) @app.after_request def after_request(response): logger.info(f"Request:{request}") logger.info(f"Request json:{request.get_json(silent=True)}") response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') return response
"""Rest api endpoints""" from flask_restx import Api from rest_api.apis import ( entities, groupings, groups, ) from rest_api.models.error import get_model as get_error_model from rest_api.exceptions import ErrorResponse api = Api(title="Image Organizer", doc="/documentation") api.add_namespace(entities.api, "/entities") api.add_namespace(groupings.api, "/groupings") api.add_namespace(groups.api, "/groups") ErrorModel = get_error_model(api) @api.errorhandler(ErrorResponse) @api.marshal_with(ErrorModel) def error_handler(error): return error, error.code
from flask_restx import Api from .cat import api as cat_api from .dog import api as dog_api api = Api( title='Zoo API', version='1.0', description='A simple demo API', ) api.add_namespace(cat_api) api.add_namespace(dog_api)
from flask_restx import Api from flask import Blueprint from .main.controller.proyecto_controller import api as proyecto_ns from .main.controller.analisis_unitario_controller import api as analisis_ns from .main.controller.detalle_controller import api as detalle_ns from .main.controller.capitulo_controller import api as capitulo_ns from .main.controller.costo_indirecto_controller import api as costo_ns from .main.controller.item_controller import api as item_ns from .main.controller.recurso_basico_controller import api as recurso_ns blueprint = Blueprint('api', __name__) api = Api(blueprint, title="Rest Flask", version='1.0', description='Presupuesto') api.add_namespace(proyecto_ns, path='/proyecto') api.add_namespace(analisis_ns, path='/analisis') api.add_namespace(detalle_ns, path='/detalle') api.add_namespace(capitulo_ns, path='/capitulo') api.add_namespace(item_ns, path='/item') api.add_namespace(costo_ns, path='/costo') api.add_namespace(recurso_ns, path='/recurso')
prices = pd.read_csv( os.path.join(os.path.dirname(__file__), "prices.csv"), index_col=0, parse_dates=True, ) # Configure the Flask app using RestX for swagger documentation app = Flask(__name__) app.config["SWAGGER_UI_DOC_EXPANSION"] = "list" app.config["RESTX_MASK_SWAGGER"] = False app.config["ERROR_INCLUDE_MESSAGE"] = False api = Api( app, version="0.1.0", title="Stocks API", description="The Stocks API provides pricing and volatility data for a " "limited number of US equities from 2010-2018", ) ns = api.namespace("stocks") # Define stock and price models for marshalling and documenting response objects tickers_model = ns.model( "Tickers", { "tickers": fields.List( fields.String(description="Ticker of the stock"), description="All available stock tickers", ), },
from flask_restx import Api from flask_jwt_extended import JWTManager from hancock.auth_utils import AuthManager import logging from logging.handlers import RotatingFileHandler import os from flask_cors import CORS app = Flask(__name__) app.config.from_object(Config) api = Api(app, version='0.1', title='Hancock API', description='REST API to return presigned URLs', prefix='/api', doc='/api', validate=True, default='Hancock') jwt = JWTManager(app) #use cors to be able to connect from catanie if app.config['CORS_RESOURCES']: cors = CORS(app, resources=app.config['CORS_RESOURCES']) else: cors = CORS(app) auth_manager = AuthManager(app) if not app.debug:
from config.settings import CONFIG from flask import Blueprint from flask_restx import Api from service.LoggerService import loggerService from models.message import message_model_definition, message_card_model, facts_model from api.endpoints.teams import api as ns_teams from api.endpoints.users import api as ns_users loggerService.info("initializing blueprint api v1") blueprint = Blueprint("api version 1", __name__, url_prefix='/api/v1') api = Api(blueprint, title='API v1', version=CONFIG['RESTX']['VERSION']['V1']) api.add_namespace(ns_teams) api.add_namespace(ns_users)
"""This is used to group all the namespaces and tells Python that the directory should be treated as a package""" from flask_restx import Api from .todo import ns as ns1 api = Api(title='Todo API', version='1.0', description='A simple Todo API', # All API metadatas ) api.add_namespace(ns1)
from flask import make_response from flask_restx import Api from core.transformer import XmlTransformer from .cognito import api as cognito from .expense import api as expense from .user import api as user api = Api( version="0.1", title="Greevil", description= "APIs For Money Management, Expense Tracking, Financial Tools and User Management" ) @api.representation('application/xml') def xml(data, code, headers): resp = make_response(str(XmlTransformer(data)), code) resp.headers.extend(headers) return resp api.add_namespace(user) api.add_namespace(expense) api.add_namespace(cognito)
from .main.controller.auth_controller import api as auth_ns blueprint = Blueprint('api', __name__) authorizations = { 'Bearer Auth': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' }, } api = Api(blueprint, title='FLASK RESTPLUS API BOILER-PLATE WITH JWT', version='1.0', description='a boilerplate for flask restplus web service', security='Bearer Auth', authorizations=authorizations ) api.add_namespace(user_ns, path='/user') api.add_namespace(auth_ns) # Global Error Handlers: @api.errorhandler(IntegrityError) def integrity_exception_handler(error: IntegrityError): """Default error handler""" return {'message': error.args}, 500
get_comments, post_comment, edit_comment, delete_comment, vote_comment, clear_vote ) from JobTracker.exceptions import InvalidUserInput from JobTracker.utils.colourisation import printColoured from flask_restx import Resource, Api, fields comment_router = Blueprint("comment", __name__) comment_api = Api( comment_router, doc="/doc", title="Comments", description="Routes for comments", default="/api/comment", default_label="Comments", ) @comment_api.route("/") class Comment(Resource): def get(self): """ Gets the comments SENT TO a given user Parameters: - user_id """ printColoured(" * Fetching list of all comments for a user", colour="yellow") request_params = dict(request.args) user_id = request_params["user_id"]