Write a restful API in Python

Source: Internet
Author: User
Tags call back

#-*-Coding:utf-8-*-# Brew Tea "" "Package.module ~~~~~~~~~~~~~~ Python implements a restful API for books. Refer to RESTful design Guide url:http://www.ruanyifeng.com/blog/2014/05/restful_api.html RESTful API General mode: GET (SELECT): Remove resources from the server (one or more items). POST (Create): Creates a new resource on the server. PUT (UPDATE): Updates the resource on the server (the client provides a full resource after the change). PATCH (UPDATE): Updates the resource on the server (the client provides changed properties). Delete: Deletes a resource from the server. Note: There is no storage persistence, in order to implement the example, it should actually be taken from the database, and the add-on method should also call back-end method. : Copyright: (c) year by Zwhset. : License:gomeops, see license_file for more details. "" " From flask import flask, request, jsonifyimport Randomapp = Flask (__name__) Books = [Dict (id=1, Isdn=random.randrange (1, 1 , title= ' A python book ', Author=dict (name= ' l0set ', city= ' Hunan '), Dict (id=2, Isdn=random.randrange (1, +), title = ' A Golang book ', Author=dict (name= ' zwhset ', city= ' Beijing '))]# error Action@app.errorhandler (405) def page_not_found ( E): Return Jsonify (Dict (code=1, message= ' method error. ')), 405# get all Books@app.route ('/api/books ') def handle_books () : Return jsonify (Books) # Get a book@app.roUte ('/api/book/<int:id> ') def handle_book (ID): For i, book in Enumerate (books): If book[' id '] = = Id:return Jsonify (b Ook) return jsonify (Dict (code=2, message= "Don ' t Fund the Book") # Create a new Book@app.route ('/api/book ', methods=[' POST ']) def Create_book (): book = Request.json # Check params if (not the ' title ' in the book and ' Author ' on book) or (not isinstance (book[' author '), Dict) or (not ' name ' in book[' author ' "and ' City ' in book[' author ')): Return Jsonify (code=3, message= ' JSON author error. ') # CR Eate a new book book[' id '] = random.randrange (1, 10000) book["ISDN" = Random.randrange (1, 10000) books.append (book) retur N Jsonify (code=0, message= ' success ') # Update book@app.route ('/api/book/<int:id> ', methods=[' PUT ') def Update_ Book (ID): book = Request.json # Check for params if (not the ' title ' in the book and ' Author ' on book) or (Not isinstance (book[' Autho R '], Dict)) or (not ' name ' in book[' author ' "and" City "in book[' Author ')): Return Jsonify (code=3, message= ' JSON author E Rror. ')# Security considerations, only take the data, others do not book_data = Dict (title=book[' title '), Author=dict (name=book[' author ' [' Name '], city=book[' author ' [' City '])))-For me, book in Enumerate (books): # Check ID if book[' id '] = = Id:books[i].update (book_data) # Update operation return Jsonify (code=0, message= ' success ') return Jsonify (Dict (code=2, message= "Don ' t Fund the Book")) # Delete a book@app.route ( '/api/book/<int:id> ', methods=[' DELETE ') def delete_book (id): For me, book in Enumerate (books): # Check ID if book[' I d '] = = Id:del books[i] # Delete book return jsonify (code=0, message= ' success ') return Jsonify (Dict (code=2, message= "Don t Fund th E book ")) if __name__ = = ' __main__ ': App.run (host= ' 0.0.0.0 ', port=8000)

Write a restful API in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.