当前位置:网站首页>Take you to API development by hand
Take you to API development by hand
2022-07-01 14:41:00 【A drop in the universe】
introduction

In this paper , You will learn how to use Flask、SQLite 3( Easy database ) and JSON Create... For data communication REST API.
This article USES the 4 The most commonly used HTTP Verb :GET、POST、PUT and DELETE, Corresponding database CRUD operation .
For example, it manages a game database games.db, Include name (name)、 Price (price) And rank (rate).
We will also use Flask Created API Expose several operations :
Get all games Create a new game Update game Delete game adopt ID Get games
First , We will use Python Create database related CRUD, Then we will be in API Use in Flask Expose all these functions , The encoding format is JSON.
install SQLite
Click on here , Download the corresponding of your system SQLite edition , This article takes Windows For example :

After downloading, the files in these two compressed packages Unzip to C Under a directory on the disk :

And add the directory to the environment variable :

see SQLite3 edition :
λ sqlite3
SQLite version 3.38.5 2022-05-06 15:25:27
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite>
Create database
Use sqlite3 databaseName.db Command to create a SQLite database , This article creates a games.db database :
λ sqlite3 games.db
SQLite version 3.38.5 2022-05-06 15:25:27
Enter ".help" for usage hints.
sqlite> .databases
main: C:\Program Files\cmder\games.db r/w
Create table
CREATE TABLE IF NOT EXISTS games(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
rate INTEGER NOT NULL
)
establish db.py
As we saw in the previous step, the database will be called games.db . newly build Python Of SQLite3 Connection file db.py:
import sqlite3
DATABASE_NAME = "games.db"
# Get database connection
def get_db():
conn = sqlite3.connect(DATABASE_NAME)
return conn
# Create database tables
def create_tables():
tables = [
"""
CREATE TABLE IF NOT EXISTS games (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
rate INTEGER NOT NULL
)
"""
]
db = get_db()
cursor = db.cursor()
for table in tables:
cursor.execute(table)
in , Besides , We have two functions :
One of them is get_db(): Used to obtain a database connectionAnother function create_tables(): WhengamesCreate a database table when the database table does not exist .
Now we have defined the database , Let's see how to use SQLite3 Database game CRUD operation .
establish game_controller.py
stay API Before exposing the database in , We will create a game controller , It will be responsible for preserving 、 to update 、 All operations of deleting and acquiring game data .
All of these functions are in a file called game_controller.py In the file of , It looks something like this :
from db import get_db
def insert_game(name, price, rate):
db = get_db()
cursor = db.cursor()
statement = "INSERT INTO games(name, price, rate) VALUES (?, ?, ?)"
cursor.execute(statement, [name, price, rate])
db.commit()
return True
def update_game(id, name, price, rate):
db = get_db()
cursor = db.cursor()
statement = "UPDATE games SET name = ?, price = ?, rate = ? WHERE id = ?"
cursor.execute(statement, [name, price, rate, id])
db.commit()
return True
def delete_game(id):
db = get_db()
cursor = db.cursor()
statement = "DELETE FROM games WHERE id = ?"
cursor.execute(statement, [id])
db.commit()
return True
def get_by_id(id):
db = get_db()
cursor = db.cursor()
statement = "SELECT id, name, price, rate FROM games WHERE id = ?"
cursor.execute(statement, [id])
return cursor.fetchone()
def get_games():
db = get_db()
cursor = db.cursor()
query = "SELECT id, name, price, rate FROM games"
cursor.execute(query)
return cursor.fetchall()
In the document , We see several functions . insert_game Function to receive game data and insert it into the database (INSERT); All of these use prepared statements to prevent us from using Python and Flask Created this API Medium SQL Inject .
We also see other ways , for example update_game perform UPDATE Action to update the game ,delete_game From its id Delete game (DELETE),get_by_id From its id Return to the game ( Use SELECT operation ).
Finally, let's take a look at returning to all existing games get_games function .
Please note that , All functions use databases and cursors to perform all operations . Now we have the database operation CRUD, It's time to use Flask Open API All the contents of the
establish main.py

install flask

You can check the official Installation help :
$ pip install Flask
We are API The first thing to do in is to create Flask Application and import game controller . We also imported a function from the database , Because we need to create tables when we start the application :
from flask import Flask, jsonify, request
import game_controller
from db import create_tables
app = Flask(__name__)
And then use GET、PUT、POST and DELETE http Verb definition route :
@app.route('/games', methods=["GET"])
def get_games():
games = game_controller.get_games()
return jsonify(games)
@app.route("/game", methods=["POST"])
def insert_game():
game_details = request.get_json()
name = game_details["name"]
price = game_details["price"]
rate = game_details["rate"]
result = game_controller.insert_game(name, price, rate)
return jsonify(result)
@app.route("/game", methods=["PUT"])
def update_game():
game_details = request.get_json()
id = game_details["id"]
name = game_details["name"]
price = game_details["price"]
rate = game_details["rate"]
result = game_controller.update_game(id, name, price, rate)
return jsonify(result)
@app.route("/game/<id>", methods=["DELETE"])
def delete_game(id):
result = game_controller.delete_game(id)
return jsonify(result)
@app.route("/game/<id>", methods=["GET"])
def get_game_by_id(id):
game = game_controller.get_by_id(id)
return jsonify(game)
Each route corresponds to the game controller function we created earlier , And SQLite3 Database interaction .
When updating and inserting games , We use get_jsonRead the requested JSON , Then visit the dictionary :
game_details = request.get_json()
Delete or pass ID Get the case , We read from the route id Variable as And receive it in the method :
game = game_controller.get_by_id(id)
this Python API adopt JSON communicate , So all responses are based on jsonify The contents returned by the function :
return jsonify(result)
Last , We created Flask Application to start the server and listen for requests :
if __name__ == "__main__":
create_tables()
"""
Here you can change debug and port
Remember that, in order to make this API functional, you must set debug in False
"""
app.run(host='0.0.0.0', port=8000, debug=False)
thus , We have complete main.py Function as follows :
from flask import Flask, jsonify, request, json
import game_controller
from db import create_tables
app = Flask(__name__)
@app.route('/games', methods=["GET"])
def get_games():
games = game_controller.get_games()
return jsonify(games)
@app.route("/game", methods=["POST"])
def insert_game():
game_details = json.loads(request.get_data())
name = game_details["name"]
price = game_details["price"]
rate = game_details["rate"]
result = game_controller.insert_game(name, price, rate)
return jsonify(result)
@app.route("/game", methods=["PUT"])
def update_game():
game_details = request.get_json()
id = game_details["id"]
name = game_details["name"]
price = game_details["price"]
rate = game_details["rate"]
result = game_controller.update_game(id, name, price, rate)
return jsonify(result)
@app.route("/game/<id>", methods=["DELETE"])
def delete_game(id):
result = game_controller.delete_game(id)
return jsonify(result)
@app.route("/game/<id>", methods=["GET"])
def get_game_by_id(id):
game = game_controller.get_by_id(id)
return jsonify(game)
"""
Enable CORS. Disable it if you don't need CORS
"""
@app.after_request
def after_request(response):
response.headers["Access-Control-Allow-Origin"] = "*" # <- You can change "*" for a domain for example "http://localhost"
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PUT, DELETE"
response.headers["Access-Control-Allow-Headers"] = "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"
return response
if __name__ == "__main__":
create_tables()
"""
Here you can change debug and port
Remember that, in order to make this API functional, you must set debug in False
"""
app.run(host='0.0.0.0', port=8000, debug=False)
It is worth noting that , Here we add CORS, If you want to start with API Different domains use this API, You need to enable CORS. Just add the following code snippet to API( In the repository , You will find the added code , You can delete it as needed ):
"""
Enable CORS. Disable it if you don't need CORS
"""
@app.after_request
def after_request(response):
response.headers["Access-Control-Allow-Origin"] = "*" # <- You can change "*" for a domain for example "http://localhost"
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PUT, DELETE"
response.headers["Access-Control-Allow-Headers"] = "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"
return response
Start the program and test
Use python3 main.py, Run our server and API :
* Serving Flask app 'main' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses (0.0.0.0)
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://127.0.0.1:8000
* Running on http://10.26.4.188:8000 (Press CTRL+C to quit)
For the convenience of all the API Test of , Use to Apifox As an interface testing tool :

GET Get all game tests
visit http://127.0.0.1:8000/games. return 200 OK, But there are no games in the database , So return null JSON character string :

POST Add a game test
Because of the game id Since the increase , So you just need to send it to the external server name, price and rate:

The server background displays as follows :
127.0.0.1 - - [16/Jun/2022 14:51:05] "POST /game HTTP/1.1" 200 -
PUT Modify the game content test
View all our current game content :

And then LOL The name of is changed to Hero alliance , At this point, we need to pass in four parameters :id,name, price, rate, Because according to id To find the game we want to change :
{
"id": 2,
"name": " Hero alliance ",
"price": 1,
"rate": 99
}
The test success is as follows :

GET Get a single game content test
In order to check just for id by 2 Whether the game was renamed successfully , We can pass in http://127.0.0.1:8000/game/2 route :

You can see ,PUT And current GET Requests are all OK Of .
DELETE Delete game test
Last , Come to our delete link , hold id by 3 Game content deleted :

You can see that the deletion was successful , our API The test is complete OK Of

summary
Last , It is time for this article to make a summary .
This tutorial uses Python、SQLite3、Flask A simple game Rest API function , By means of Flask Process incoming HTTP Four requests for :GET、POST、PUT、DELETE, The most basic functions of adding, deleting, modifying and querying are realized .
The use of Apifox As our interface testing tool , A complete experience of a simple API Development process .
If the article is useful to you , Just like it before you leave , See you for the next article .
边栏推荐
- Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server
- sqlilabs less9
- sqlilabs less13
- Problem note - Oracle 11g uninstall
- 券商万1免5证券开户是合理安全的吗,怎么讲
- Provincial election + noi Part 10 probability statistics and polynomials
- Distributed dynamic (collaborative) rendering / function runtime based on computing power driven, data and function collaboration
- When the main process architecture game, to prevent calls everywhere to reduce coupling, how to open the interface to others to call?
- [stage life summary] I gave up the postgraduate entrance examination and participated in the work. I have successfully graduated and just received my graduation certificate yesterday
- So programmers make so much money doing private work? It's really delicious
猜你喜欢

2022-2-15 learning the imitation Niuke project - Section 3 post details

一波三折,终于找到src漏洞挖掘的方法了【建议收藏】

241. 为运算表达式设计优先级

【商业终端仿真解决方案】上海道宁为您带来Georgia介绍、试用、教程

"National defense seven sons" funding soared, with Tsinghua reaching 36.2 billion yuan, ranking second with 10.1 billion yuan. The 2022 budget of national colleges and universities was made public

sqlilabs less-8
![[dynamic programming] interval dp:p1005 matrix retrieval](/img/c9/2091f51b905d2c0ebc978dab3d34d3.jpg)
[dynamic programming] interval dp:p1005 matrix retrieval

Salesforce, Johns Hopkins, Columbia | progen2: exploring the boundaries of protein language models

Vnctf2022 open web gocalc0

Don't want to knock the code? Here comes the chance
随机推荐
2022-2-15 learning the imitation Niuke project - post in Section 2
Halo effect - who says that those with light on their heads are heroes
Research Report on the development trend and competitive strategy of the global diamond suspension industry
【牛客网刷题系列 之 Verilog快速入门】~ 多功能数据处理器、求两个数的差值、使用generate…for语句简化代码、使用子模块实现三输入数的大小比较
对于编程思想和能力有重大提升的书有哪些?
Open source internship experience sharing: openeuler software package reinforcement test
Blog recommendation | in depth study of message segmentation in pulsar
使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片,并存储到指定服务器
既不是研发顶尖高手,也不是销售大牛,为何偏偏获得 2 万 RMB 的首个涛思文化奖?
Use of Oracle database objects
Semiconductor foundation of binary realization principle
Basis of target detection (NMS)
One of the data Lake series | you must love to read the history of minimalist data platforms, from data warehouse, data lake to Lake warehouse
So programmers make so much money doing private work? It's really delicious
Research Report on the development trend and competitive strategy of the global electromagnetic flowmeter industry
241. Design priorities for operational expressions
使用net core 6 c# 的 NPOI 包,讀取excel..xlsx單元格內的圖片,並存儲到指定服務器
qt捕获界面为图片或label显示
Music player development example (can be set up)
[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial