Main.py
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
class DemoApiEndpoint(Resource):
def __init__(self):
self.post_args = reqparse.RequestParser()
self.post_args.add_argument("name",
type=str,
help="You must include a name string with this post request.",
required=True)
def get(self):
return {
"message": "This is a response from a GET request."
}
def post(self):
args = self.post_args.parse_args()
name = args['name']
return {
"message": f'Nice to meet you, {name}!'
}
api.add_resource(DemoApiEndpoint, "/api/DemoApiEndpoint")
if __name__ == '__main__':
app.run(host="0.0.0.0", port=80, debug=True)
tests/test_home_route.py
from main import app
def test_home_route():
response = app.test_client().get('/')
assert response.status_code == 200
assert b"Hello, World!" in response.data
tests/test_demo_api_endpoint.py
from main import app
def test_get_api_endpoint():
with app.test_client() as c:
response = c.get('api/DemoApiEndpoint')
assert response.status_code == 200
json_response = response.get_json()
assert json_response == {'message': 'This is a response from a GET request.'}
def test_post_api_endpoint():
with app.test_client() as c:
response = c.post('api/DemoApiEndpoint', json={
"name": "Vincent"
})
assert response.status_code == 200
json_response = response.get_json()
assert json_response == {'message': 'Nice to meet you, Vincent!'}
# test_api_endpoint()
# test_post_api_endpoint()
Comments
Post a Comment