This tutorial concludes a three-part series on building RESTful APIs with Flask, demonstrating an ORM-agnostic approach using Flask-Restful. Unlike the previous installments which relied on SQLAlchemy, this method abstracts the Object-Relational Mapper (ORM), offering flexibility to work with any ORM.
The example application remains consistent for clarity, although it uses SQLAlchemy internally. The tutorial showcases how to adapt this approach to other ORMs.
Dependency Installation
To begin, install the necessary dependency:
pip install Flask-Restful
Application Setup
Remove any code from the previous tutorial parts for a clean start. The application configuration is modified as follows:
flask_app/my_app/__init__.py
from flask import Flask from flask_restful import Api app = Flask(__name__) api = Api(app)
flask_app/my_app/product/views.py
import json from flask import request, Blueprint, abort from my_app import db, app, api from my_app.product.models import Product from flask_restful import Resource, reqparse catalog = Blueprint('catalog', __name__) parser = reqparse.RequestParser() parser.add_argument('name', type=str) parser.add_argument('price', type=float) @catalog.route('/') @catalog.route('/home') def home(): return "Welcome to the Catalog Home." # FLASK RESTFUL ENDPOINTS class ProductApi(Resource): def get(self, id=None, page=1): if not id: products = Product.query.paginate(page, 10).items else: products = [Product.query.get(id)] if not products: abort(404) res = {} for product in products: res[product.id] = { 'name': product.name, 'price': product.price, } return json.dumps(res) def post(self): args = parser.parse_args() name = args['name'] price = args['price'] product = Product(name, price) db.session.add(product) db.session.commit() res = {} res[product.id] = { 'name': product.name, 'price': product.price, } return json.dumps(res) api.add_resource( ProductApi, '/api/product', '/api/product/<id>', '/api/product/<id>/<page>' )</page></id></id>
reqparse
handles form data validation.
Testing
Testing is identical to the previous tutorial. The routing URLs remain unchanged.
Conclusion
This final part demonstrates building ORM-independent RESTful APIs with Flask, completing the series. Further exploration of the covered methods is encouraged, building upon the foundational knowledge presented.
This post includes contributions from Esther Vaati, a software developer and writer for Envato Tuts .
The above is the detailed content of Building RESTful APIs With Flask: ORM Independent. For more information, please follow other related articles on the PHP Chinese website!

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools
