MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Building JSON APIs with jsonify & Status Codes0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
8.1Building JSON APIs with jsonify & Status Codes8.2Data Serialization & Validation with Marshmallow8.3Stateless JWT Authentication with Flask-JWT-Extended
HomeTutorialsFlaskBuilding JSON APIs with jsonify & Status Codes
Data Serialization & Validation with Marshmallow

Building JSON APIs with jsonify & Status Codes

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Modern web and mobile architectures frequently separate the backend from the frontend: Flask serves as a stateless RESTful API, communicating with Next.js, React, or mobile clients via JSON.

Flask provides built-in utilities—primarily jsonify()—to construct robust API contracts adhering to RFC standards.


1. Understanding jsonify() vs json.dumps()

Python includes a standard json library, but you should always use Flask's jsonify() when building web APIs:

FeatureStandard json.dumps()Flask jsonify()
Output TypePlain Python stringFully formed Response object
HeaderContent-Type: text/html (default)Content-Type: application/json
Status CodeRequires manual wrappingSupports tuple syntax: jsonify(...), 201
Order PreservationMay reorder keysRespects JSON serialization configurations
1from flask import Flask, jsonify, request
2 
3app = Flask(__name__)
4 
5@app.route("/api/v1/health")
6def health_check():
7 return jsonify({
8 "status": "healthy",
9 "uptime_seconds": 3600,
10 "database": "connected"
11 }), 200

2. Standardizing API Response Envelopes

Enterprise APIs should adopt a consistent JSON response envelope for both success and error states:

1def api_response(data=None, message="Success", status_code=200, error=None):
2 payload = {
3 "success": error is None,
4 "message": message,
5 "data": data,
6 "error": error
7 }
8 return jsonify(payload), status_code

Usage Examples:

1@app.route("/api/v1/students/<int:student_id>")
2def get_student(student_id):
3 student = Student.query.get(student_id)
4 if not student:
5 return api_response(
6 message="Resource not found",
7 error={"code": "STUDENT_NOT_FOUND", "id": student_id},
8 status_code=404
9 )
10
11 return api_response(
12 data={"id": student.id, "name": student.name, "email": student.email},
13 status_code=200
14 )

3. Parsing Incoming JSON Data

Always validate incoming payloads when processing POST, PUT, or PATCH requests:

1@app.route("/api/v1/students", methods=["POST"])
2def create_student():
3 # 1. Verify JSON Content-Type
4 if not request.is_json:
5 return jsonify({"error": "Content-Type must be application/json"}), 415
6 
7 # 2. Extract JSON payload
8 data = request.get_json(silent=True)
9 if not data:
10 return jsonify({"error": "Malformed or empty JSON body"}), 400
11 
12 # 3. Validate required fields
13 required_fields = ["name", "email"]
14 missing = [f for f in required_fields if f not in data or not str(data[f]).strip()]
15 if missing:
16 return jsonify({"error": f"Missing required fields: {', '.join(missing)}"}), 422
17 
18 # 4. Persist
19 new_student = Student(name=data["name"], email=data["email"])
20 db.session.add(new_student)
21 db.session.commit()
22 
23 return jsonify({"id": new_student.id, "name": new_student.name}), 201

4. HTTP Status Code Best Practices for APIs

  • 200 OK: Successful GET, PUT, or PATCH.
  • 201 Created: Successful POST that created a new database entity.
  • 204 No Content: Successful DELETE operation (no response body).
  • 400 Bad Request: Malformed syntax (e.g. invalid JSON).
  • 401 Unauthorized: Client lacks valid authentication credentials.
  • 403 Forbidden: Client is authenticated but lacks required permission.
  • 404 Not Found: Target resource URI does not exist.
  • 415 Unsupported Media Type: Client failed to send Content-Type: application/json.
  • 422 Unprocessable Entity: Valid JSON, but fails business validation rules (e.g. password too short).

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What HTTP response header is automatically set when returning jsonify(...)?
Question 2
What status code should be returned when a client sends XML to an endpoint that strictly expects JSON?
Question 3
What property on the Flask request object checks if the incoming request has an application/json Content-Type?
Question 4
When a resource is successfully deleted in a RESTful API, what status code is standard when returning an empty body?
Question 5
What status code is appropriate when a JSON payload is well-formed, but a field fails business logic (e.g. negative age value)?
Next Lesson

Data Serialization & Validation with Marshmallow

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
The Application Factory Pattern (create_app)Data Serialization & Validation with Marshmallow

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext