Create API

Creating Your Own REST API with Flask

Introduction

In this post, we’ll explore how to create a simple RESTful API using the Flask framework. Flask is a micro web framework for Python that allows you to quickly build web applications and APIs. By the end of this tutorial, you’ll have a basic understanding of how to design and build your own REST API, create endpoints, handle different HTTP methods, and test your API locally.


1. Setting Up Flask

Before we start building the API, you’ll need to install Flask. If you don’t have it installed already, you can do so using pip:

bash
Copy code
pip install flask

Once Flask is installed, you can begin by importing it into your Python script.


2. Creating a Simple Flask API

A REST API typically exposes several endpoints that can handle different HTTP methods like GET, POST, PUT, DELETE, etc. Let’s start by building a basic API with a single GET endpoint.

Example: Hello World API

Create a Python file, say app.py, and add the following code:

python
Copy code
from flask import Flask

app = Flask(__name__)

@app.route('/hello', methods=['GET'])
def hello():
    return {"message": "Hello, World!"}

if __name__ == '__main__':
    app.run(debug=True)

Explanation:

  • We import Flask from the flask library.
  • We create a Flask app instance using Flask(__name__).
  • The @app.route() decorator is used to define a route and associate it with a function. Here, we are creating a GET endpoint at the /hello URL.
  • The hello() function returns a simple JSON response: {"message": "Hello, World!"}.
  • Finally, we call app.run(debug=True) to start the Flask development server in debug mode.

To run the app, navigate to the directory containing app.py and run:

bash
Copy code
python app.py

This will start the Flask development server at http://127.0.0.1:5000/.

You can open your browser and visit http://127.0.0.1:5000/hello to see the output.

Output:

json
Copy code
{
    "message": "Hello, World!"
}

3. Handling Different HTTP Methods

Flask allows you to handle various HTTP methods (GET, POST, PUT, DELETE) by specifying them in the @app.route() decorator. Let’s modify our API to include more functionality by adding a POST endpoint.

Example: Handling POST Requests

python
Copy code
from flask import Flask, request

app = Flask(__name__)

# Example of a GET endpoint
@app.route('/hello', methods=['GET'])
def hello():
    return {"message": "Hello, World!"}

# Example of a POST endpoint
@app.route('/greet', methods=['POST'])
def greet():
    data = request.get_json()  # Parse the incoming JSON data
    name = data.get("name", "Guest")
    return {"message": f"Hello, {name}!"}

if __name__ == '__main__':
    app.run(debug=True)

Explanation:

  • The @app.route('/greet', methods=['POST']) decorator is used to define a POST endpoint.
  • Inside the greet() function, we use request.get_json() to parse the incoming JSON data.
  • We extract the "name" field from the JSON data and return a personalized greeting message.
  • If no "name" field is provided, we default to “Guest”.

To test this endpoint, use a tool like Postman or cURL to send a POST request with a JSON payload:

json
Copy code
{
    "name": "Alice"
}

Response:

json
Copy code
{
    "message": "Hello, Alice!"
}

4. Handling URL Parameters

In many APIs, you may want to accept dynamic values in the URL. Flask allows you to easily capture URL parameters. Let’s create an endpoint that accepts a user’s name in the URL and responds with a personalized message.

Example: URL Parameters

python
Copy code
@app.route('/greet/<name>', methods=['GET'])
def greet_user(name):
    return {"message": f"Hello, {name}!"}

Explanation:

  • The <name> in the route /greet/<name> is a placeholder for the URL parameter.
  • When the API is called, Flask captures the value of <name> and passes it to the greet_user() function as an argument.

To test this, visit http://127.0.0.1:5000/greet/Alice in your browser or use cURL:

bash
Copy code
curl http://127.0.0.1:5000/greet/Alice

Response:

json
Copy code
{
    "message": "Hello, Alice!"
}

5. Returning Different Response Types

Flask allows you to return responses in various formats. While JSON is the most common, you can return HTML, plain text, or even files. Let’s look at how to return an HTML response from an endpoint.

Example: Returning HTML

python
Copy code
@app.route('/html', methods=['GET'])
def html_response():
    return "<h1>Hello, World!</h1>"

Now, visiting http://127.0.0.1:5000/html will return an HTML response with a simple heading:

html
Copy code
<h1>Hello, World!</h1>

6. Testing the API

Once your API is built, it’s important to test it to ensure everything works as expected. Flask comes with a built-in testing client that makes it easy to write tests for your endpoints.

Example: Writing Tests for Your API

python
Copy code
import unittest
from app import app  # Import the app instance

class FlaskTestCase(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()

    def test_hello(self):
        response = self.app.get('/hello')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json, {"message": "Hello, World!"})

    def test_greet(self):
        response = self.app.post('/greet', json={"name": "Alice"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json, {"message": "Hello, Alice!"})

if __name__ == '__main__':
    unittest.main()

Explanation:

  • test_client() creates a test client to simulate requests to your API.
  • In the test methods (test_hello and test_greet), we use the test client to send GET and POST requests to the API and assert that the responses are correct.

7. Conclusion

You’ve now learned the basics of creating a REST API with Flask. You can create endpoints that handle different HTTP methods, parse parameters, and return various types of responses. Flask is a great framework for building APIs quickly and efficiently, and it’s perfect for small to medium-sized applications.