Skip to content

Commit c6189a0

Browse files
committed
Working Flask Endpoints
1 parent 3b61aa0 commit c6189a0

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

app.py

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
from flask import Flask, request, jsonify
2+
from flask_sqlalchemy import SQLAlchemy
3+
from flask_marshmallow import Marshmallow
4+
import os
5+
app = Flask(__name__)
6+
7+
basedir = os.path.abspath(os.path.dirname(__file__))
8+
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.sqlite')
9+
db = SQLAlchemy(app)
10+
ma = Marshmallow(app)
11+
12+
#inherits from the SQULAlchemy(app) object
13+
class Guide(db.Model):
14+
id = db.Column(db.Integer, primary_key=True)
15+
title = db.Column(db.String(100), unique=False)
16+
content = db.Column(db.String(144), unique=False)
17+
18+
def __init__(self, title, content):
19+
self.title = title
20+
self.content = content
21+
22+
class GuideSchema(ma.Schema):
23+
class Meta:
24+
fields = ('title', 'content')
25+
26+
27+
guide_schema = GuideSchema()
28+
guides_schema = GuideSchema(many=True)
29+
30+
#Endpoint to Create a New Guide
31+
@app.route('/guide', methods=["POST"])
32+
def add_guide():
33+
#request is imported from the flask library
34+
title = request.json['title']
35+
content = request.json['content']
36+
37+
new_guide = Guide(title, content)
38+
39+
db.session.add(new_guide)
40+
db.session.commit()
41+
#After committing, see if the entry is there
42+
guide = Guide.query.get(new_guide.id)
43+
return guide_schema.jsonify(guide)
44+
45+
46+
#Endpoint to query all guides
47+
@app.route("/guides", methods=["GET"])
48+
def get_guides():
49+
all_guides= Guide.query.all()
50+
result = guides_schema.dump(all_guides)
51+
return jsonify(result)
52+
53+
#Endpoint to query for a single guide
54+
@app.route("/guide/<id>", methods=["GET"])
55+
#parameter id comes from the URL variable <id>
56+
def get_guide(id):
57+
single_guide = Guide.query.get(id)
58+
return guide_schema.jsonify(single_guide)
59+
60+
#Endpoint to update a single guide
61+
@app.route("/guide/<id>", methods=["PUT"])
62+
def update_guide(id):
63+
guide = Guide.query.get(id)
64+
title = request.json['title']
65+
content = request.json['content']
66+
guide.title = title
67+
guide.content = content
68+
db.session.commit()
69+
return guide_schema.jsonify(guide)
70+
71+
#Endpoint for deleting a guide
72+
@app.route("/guide/<id>", methods=["DELETE"])
73+
def delete_guide(id):
74+
guide = Guide.query.get(id)
75+
db.session.delete(guide)
76+
db.session.commit()
77+
return guide_schema.jsonify(guide)
78+
79+
if __name__ == '__main__':
80+
app.run(debug=True)

app.sqlite

8 KB
Binary file not shown.

0 commit comments

Comments
 (0)