🚀 Full Stack Development – Session 10

Mastering HTML Forms and Backend Integration: Key Takeaways from Full Stack Development Session 10

As I continue my journey through full stack development, Session 10 brought some exciting insights into working with HTML forms, file uploads, and Flask-powered backends. This session deepened my understanding of how frontend and backend technologies seamlessly interact to handle data submissions, including both simple form data and file uploads. Here’s a professional breakdown of what I learned, complete with practical examples, to help fellow developers or aspiring full stack enthusiasts gain actionable knowledge.


1. HTML Forms and the POST Method

One key revelation from this session was that HTML forms natively support only the GET and POST methods, with POST being the go-to choice for sending data securely to a backend. Unlike GET, which appends data to the URL, POST encapsulates it in the request body, making it ideal for sensitive or larger datasets.

I created a simple HTML form to send data to a Flask backend using the POST method. Here’s an example of the form I built:

<form action="/student/create" method="POST">
    Name :  <input type="text" name ="name">
    <br>
    Mobile : <input type="text" name="mobile">
    <br>
    Cources : <input type="text" name="cources">
    <br>
    <button type="submit">Submit</button>
</form>        

This form sends the user’s input to the /student/create endpoint on the backend, which I’ll cover shortly.


2. Flask Backend to Handle POST Requests

On the backend, I used Flask, a lightweight Python framework, to process the incoming data. What stood out was the ability to handle both form data and raw JSON using a single URL. Flask’s request object makes this incredibly flexible.

Here’s the Flask code I wrote to handle the POST request:

from flask import Flask, request

app = Flask(__name__)

studentDB ={
                1: {
                    "id" : 1,
                    "name" : "saurabh",
                    "mobile" : 7004598475,
                    "cources" : ["QC" , "AI"]
                },

                2 : {
                    "id" : 2,
                    "name" : "Vimal",
                    "mobile" : 15812545875,
                    "cources" : ["QC" , "AI", "DSA"]
                },

                3: {
                    "id" : 3,
                    "name" : "Eric",
                    "mobile" : 4525845985,
                    "cources" : [ "AI"]
                },               
}

@app.route("/student/create", methods=['POST'])
def studentinfocreate():
    if request.form:
        result = request.form
        name = result['name']
        mobile = result['mobile']
        cources = result['cources']
       # print(result['myfile'])

        nextId =  list ( studentDB.keys( ) ) [ -1 ]  + 1 

        studentDB[nextId] = {
            "id" : nextId,
            "name" : name,
            "mobile" : mobile,
            "cources" : [cources]
        }

    
    elif request.json:
        studentDB[list ( studentDB.keys( ) ) [ -1 ]  + 1 ]  =  request.json

    else:
        print("not supported")
        return 'not supported'
    return "record created..."
if __name__ == "__main__":
    app.run(debug=True)        

This Flask app defines a simple in-memory student database (studentDB). It exposes a POST endpoint at /student/create to add new student records. The API supports two input formats:

  • HTML form data (request.form): Extracts name, mobile, and cources, generates a new ID, and adds the record.
  • JSON data (request.json): Directly adds the JSON object to the database with a new ID.

It handles both form-based and raw JSON submissions for creating new student entries.


3. File Uploads with HTML Forms

Next, I explored file uploads, a critical feature for many web applications. To enable file uploads in an HTML form, I used the <input type="file"> element and set the enctype attribute to multipart/form-data. This content type is essential for uploading files, as it allows the form to send both text data and binary files.

Here’s the updated HTML form:

<form action="/upload" method="POST" enctype="multipart/form-data">
    upload file <input type="file" name="myfile">
    <br>
    <button type="submit">Upload</button>
</form>        

The enctype="multipart/form-data" attribute tells the browser to encode the form data in a way that supports file uploads.


4. Handling File Uploads in Flask

On the Flask backend, I used request.files to access the uploaded file. This object provides a file handle (fh) with useful attributes like filename, mimetype, name, and content_length. To inspect these attributes, I used print(dir(fh)), which revealed all available methods and properties of the file object.

Here’s the Flask code to handle the file upload:

@app.route("/student/create", methods=['POST'])
def studentinfocreate():
    if 'file' not in request.files:
        return {"error": "No file part"}, 400
    fh = request.files['myfile']
    if fh.filename == '':
        return {"error": "No selected file"}, 400

    if fh.mimetype == "image/jpeg":
        fh.save(f'templates/{fh.filename}')
        return {"message": "File uploaded successfully", "filename": fh.filename}, 200

    else:
        print( "file type not supported")
    
    # Print file details for debugging
    print(dir(fh))        

output:

['__bool__', '__class__', '__delattr__', '__dict__'_le__', '__lt__', '__module__', '__ne_, '__dir__', '__doc__', '__eq__', '__format__', '__pr__', '__setattr__', '__sizeof__', '_ge__', '__getattr__', '__getattribute__', '__getsta_content_type', 'close', 'content_lengte__', '__gt__', '__hash__', '__init__', '__init_supe', 'mimetype_params', 'name', 'save'bclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_/create HTTP/1.1" 200 -ex__', '__repr__', '__setattr__', '__sizeof__', '__1" 200 -str__', '__subclasshook__', '__weakref__', '_parse_g HTTP/1.1" 404 -content_type', 'close', 'content_length', 'content_, '__dir__', '__doc__', '__eq__', '__ftype', 'filename', 'headers', 'mimetype', 'mimetype_', '__getstate__', '__gt__', '__hash__params', 'name', 'save', 'stream']         

Key points:

  • request.files['myfile'] retrieves the file from the form, where 'file' matches the name attribute in the HTML input.
  • The file is saved using the save() method, which writes it to the specified directory (e.g., templates/).
  • For simple data uploads without files, the default application/x-www-form-urlencoded content type works fine, but multipart/form-data is required for files.


5. Testing with Postman and HTML Forms

To ensure everything worked as expected, I tested the backend URLs using Postman and the HTML form:

  • Postman: I sent raw JSON to /student/create, form data to /student/create, and a file to /student/create with the multipart/form-data content type. The responses confirmed that Flask handled each case correctly.
  • HTML Form: Submitting the form in a browser successfully sent data and files to the backend, with Flask saving the uploaded files as intended.


Key Takeaways

  • Flexibility: A single Flask endpoint can handle both form data and JSON, making it versatile for different use cases.
  • File Uploads: Use multipart/form-data for files and request.files in Flask to process them.
  • Content Types: Understand when to use application/x-www-form-urlencoded (simple data) versus multipart/form-data (files).
  • Debugging: Tools like print(dir(fh)) help explore file handle properties, aiding in development.


Conclusion

Session 10 was a practical dive into the mechanics of HTML forms and Flask backend integration. Whether you’re building a simple contact form or a file upload system, these skills form the backbone of full stack development. By combining frontend forms with a robust backend, you can create dynamic, user-friendly applications that handle data efficiently.

If you’re a developer looking to enhance your full stack toolkit, try experimenting with these concepts—set up a Flask server, build a form, and test it with Postman. The hands-on experience is invaluable!


To view or add a comment, sign in

More articles by SAURABH KUMAR RANJAN

Explore content categories