I'm trying to implement a REST API with Flask-RESTful. My API contains 4 requests: GET, POST, PUT, DELETE. Everything works perfectly except for the PUT request. It keeps returning Status Code 404, which the requested URL is not found. I'm using Postman to test my API. Here is my code. Can any show me where did I do it wrong? Thank you!
# Small API project using Flask-RESTful
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
app = Flask(__name__)
# Encrypted key
app.secret_key = "Nam Dao"
api = Api(app)
students = []
class Student(Resource):
parser = reqparse.RequestParser()
parser.add_argument("major", type=str, required=True, help="This field cannot be left blank")
def get(self, name):
# filter function will return a filter object
# next function will get the "next" student in the filter object.
# if the Next function does not return anything => return None.
for student in students:
if student["name"] == name:
return student, 200
return {"message": "student not found"}, 404
def post(self, name):
if next(filter(lambda x: x["name"] == name, students), None) is not None:
return {"message": f"A student with the name {name} already exists"}, 400
request_data = self.parser.parse_args()
print(request_data)
student = {"name": name, "major": request_data["major"]}
students.append(student)
return student, 201
def delete(self, name):
for student in students:
if student["name"] == name:
students.remove(student)
return {"message": "Item deleted"}, 200
return {"message": "No student found"}, 204
def put(self, name):
data = request.get_json()
for student in students:
if student["name"] == name:
student["major"] = data["major"]
return {"message": "Student Major Changed"}, 200
student = {"name": data["name"], "major": data["major"]}
students.append(student)
return {"message": "Student Added"}, 200
api.add_resource(Student, "/student/<string:name>")
class StudentsList(Resource):
def get(self):
return {"students": students}, 200
api.add_resource(StudentsList, "/students")
if __name__ == '__main__':
app.run(debug=True)
I recheck my URL again and I was missing a letter, that's why it returns 404 Status Code. It was a very silly mistake. Everything works just fine