DEV Community

Abdul Rehman Nadeem
Abdul Rehman Nadeem

Posted on

Building a RESTful API with Flask: A Beginner's Guide

Introduction:
Welcome to the exciting world of web development with Flask! If you're just starting out on your journey to master Flask, you've come to the right place. In this guide, we'll walk through the process of building a simple RESTful API using Flask, a lightweight and powerful web framework for Python.

Prerequisites:
Before we dive into coding, make sure you have Python installed on your machine. You can install Flask using pip:

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Setting up your project:
Let's create a new directory for our project and set up a virtual environment. This helps keep your project dependencies isolated.

mkdir flask-api
cd flask-api
python -m venv venv
Enter fullscreen mode Exit fullscreen mode

Activate the virtual environment:

  • On Windows:
venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode
  • On Unix or MacOS:
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Now, let's create a simple Flask app. Create a file named app.py and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Run your app:

python app.py
Enter fullscreen mode Exit fullscreen mode

You should see your Flask app running at http://127.0.0.1:5000/. Open this URL in your browser, and you should see the "Hello, World!" message.

Building a RESTful API:
Now, let's turn our simple app into a RESTful API. We'll create endpoints for basic CRUD operations (Create, Read, Update, Delete).

  1. Creating Resources: Let's create an endpoint to handle the creation of a resource. Update your app.py file:
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/resource', methods=['POST'])
def create_resource():
    data = request.get_json()
    # Perform validation and save resource to the database
    # For now, let's just echo the data
    return jsonify(data), 201

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Test the endpoint using a tool like Postman or curl:

curl -X POST -H "Content-Type: application/json" -d '{"name": "New Resource"}' http://127.0.0.1:5000/api/resource
Enter fullscreen mode Exit fullscreen mode
  1. Reading Resources: Let's add an endpoint to retrieve the created resource:
@app.route('/api/resource/<int:resource_id>', methods=['GET'])
def get_resource(resource_id):
    # Fetch resource from the database based on resource_id
    # For now, let's just return a dummy response
    return jsonify({'id': resource_id, 'name': 'New Resource'}), 200
Enter fullscreen mode Exit fullscreen mode

Test the endpoint:

curl http://127.0.0.1:5000/api/resource/1
Enter fullscreen mode Exit fullscreen mode

Conclusion:
Congratulations! You've built a simple RESTful API with Flask. This is just the beginning—Flask offers a wide range of features to explore, such as request handling, authentication, and database integration.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay