DeveloperBreeze

In this tutorial, we will walk through the process of building a simple REST API using Flask, a lightweight and flexible web framework for Python. We will cover setting up the Flask environment, creating endpoints, handling HTTP requests, and returning JSON responses.


Introduction to REST APIs

A REST API (Representational State Transfer Application Programming Interface) is a set of rules that allow applications to communicate with each other over the web. REST APIs are commonly used to build web services and are known for their simplicity and scalability. They rely on stateless communication, typically using HTTP methods like GET, POST, PUT, DELETE, etc.


Setting Up the Flask Environment

Step 1: Install Flask

Make sure Python is installed on your machine. Then, install Flask using pip:

pip install Flask

Step 2: Create a Project Directory

mkdir flask_rest_api
cd flask_rest_api

Step 3: Create a Virtual Environment

python -m venv venv

Activate the virtual environment:

  • On Windows:
  venv\Scripts\activate
  • On macOS/Linux:
  source venv/bin/activate

Building the REST API

Step 1: Create the Flask Application

Create a file named app.py and add:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Flask REST API!"

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

Run the application:

python app.py

Visit http://127.0.0.1:5000/ in your browser to see the welcome message.


Step 2: Create an API Endpoint

from flask import Flask, jsonify

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

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

Step 3: Handle HTTP Methods (GET, POST, PUT, DELETE)

from flask import Flask, jsonify, request, abort

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    return jsonify(item)

@app.route('/api/items', methods=['POST'])
def create_item():
    if not request.json or 'name' not in request.json or 'price' not in request.json:
        abort(400)
    new_item = {
        "id": items[-1]['id'] + 1 if items else 1,
        "name": request.json['name'],
        "price": request.json['price']
    }
    items.append(new_item)
    return jsonify(new_item), 201

@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    if not request.json:
        abort(400)
    item['name'] = request.json.get('name', item['name'])
    item['price'] = request.json.get('price', item['price'])
    return jsonify(item)

@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    items.remove(item)
    return jsonify({"result": True})

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

Explanation

MethodEndpointDescription
GET/api/itemsRetrieves all items.
GET/api/items/<item_id>Retrieves a specific item by ID.
POST/api/itemsAdds a new item (requires name and price).
PUT/api/items/<item_id>Updates an existing item by ID.
DELETE/api/items/<item_id>Deletes an item by ID.

Testing the API

You can use Postman or curl to test the API.

  • Get all items:
  curl http://127.0.0.1:5000/api/items
  • Get a specific item:
  curl http://127.0.0.1:5000/api/items/1
  • Create a new item:
  curl -X POST -H "Content-Type: application/json" -d '{"name": "Item 4", "price": 250}' http://127.0.0.1:5000/api/items
  • Update an existing item:
  curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item 2"}' http://127.0.0.1:5000/api/items/2
  • Delete an item:
  curl -X DELETE http://127.0.0.1:5000/api/items/3

Conclusion

In this tutorial, we built a simple REST API using Flask that can handle basic CRUD operations. This fundamental skill is crucial for web developers and serves as a solid foundation for building more complex APIs. You can extend this by adding authentication, database integration, and deploying your Flask application to production.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
python

Build a Facial Recognition Attendance System

Capture or collect images of individuals whose attendance you want to track. Organize the images in directories named after the individuals for easy labeling.

Example folder structure:

Dec 10, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

Laravel's Http facade simplifies making POST requests to external APIs. Here’s how you can send a basic POST request with some data:

use Illuminate\Support\Facades\Http;

$response = Http::post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2',
]);

dd($response->body()); // Display the raw response body

Oct 24, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

To access and utilize the data stored in your SQLite database, you can perform SQL queries. Here's how to retrieve and display the data from the "accounts" table.

Add the following code to your app.js file within the db.serialize() block, after inserting data:

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

To allow the React frontend to communicate with Flask, we need to enable CORS. Install the Flask-CORS package:

pip install flask-cors

Sep 30, 2024
Read More
Tutorial
php

بناء API متقدم باستخدام Laravel Passport للتوثيق

ثم توجه إلى مجلد المشروع:

cd laravel-passport-api

Sep 27, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

من خلال هذا الدليل، تعلمنا كيفية تحويل الكائنات إلى JSON باستخدام JSON.stringify()، وكيفية قراءة بيانات JSON باستخدام JSON.parse()، وكذلك كيفية جلب البيانات من API والتعامل مع JSON المعقد.

نصائح إضافية:

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

With the Fetch API:

  • The fetch() method returns a Promise that resolves to the Response object representing the entire HTTP response.
  • We check if the response is successful and then parse it as JSON.
  • Any errors during the request are caught and logged.

Sep 18, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

Axios provides a variety of ways to handle responses, allowing you to work with the data returned by the server.

The response object contains several useful properties:

Sep 02, 2024
Read More
Tutorial
python

Getting Started with Pydantic: Data Validation and Type Coercion in Python

from pydantic import conint

class User(BaseModel):
    id: int
    name: str
    age: conint(ge=0, le=120)  # Age must be between 0 and 120

You can use field aliases to allow for different input names:

Aug 29, 2024
Read More
Tutorial
python

Setting Up and Managing Python Virtual Environments Using venv

To install the dependencies listed in a requirements.txt file, run:

pip install -r requirements.txt

Aug 29, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 24, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

Laravel will automatically serve the compiled assets in production, ensuring your application is optimized and ready for users.

By following this tutorial, you’ve successfully integrated Laravel and React using Vite. You learned how to set up database operations in Laravel, create API endpoints, and build a React frontend that interacts with Laravel’s backend. This setup is ideal for modern full-stack web development, allowing you to leverage Laravel’s powerful backend features with React’s dynamic frontend capabilities.

Aug 14, 2024
Read More
Tutorial
php

Integrating and Using NMI Payment Gateway in Laravel

Create a new file in the app/Services directory named NMI.php.

   namespace App\Services;

   use Illuminate\Support\Facades\Http;

   class NMI
   {
       protected $securityKey, $url;
       protected $production;

       public function __construct()
       {
           $this->production = env('APP_ENV') === 'production';
           $this->securityKey = config('nmi.security_key');
           $this->url = 'https://secure.nmi.com/api/transact.php';
       }
   }

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

The server should be running on http://localhost:8000.

You can use a tool like Postman or curl to test the endpoints.

Aug 12, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

Create an index.js file in your project directory and add the following code:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Sample data
let books = [
    { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
    { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
];

// GraphQL schema definition
const typeDefs = gql`
    type Book {
        title: String!
        author: String!
    }

    type Query {
        books: [Book]
    }

    type Mutation {
        addBook(title: String!, author: String!): Book
    }
`;

// GraphQL resolvers
const resolvers = {
    Query: {
        books: () => books,
    },
    Mutation: {
        addBook: (_, { title, author }) => {
            const newBook = { title, author };
            books.push(newBook);
            return newBook;
        },
    },
};

// Create Apollo server
const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
    console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);

Aug 12, 2024
Read More
Code
javascript json

How to Deep Clone a JavaScript Object

No preview available for this content.

Aug 12, 2024
Read More
Tutorial
python

Build a Web Application with Flask and PostgreSQL

In this tutorial, you built a basic web application using Flask and PostgreSQL. You learned how to:

  • Set up your development environment
  • Connect Flask with PostgreSQL via SQLAlchemy
  • Perform basic CRUD operations
  • Prepare your app for deployment

Aug 04, 2024
Read More
Code
json python

Python Code Snippet: Simple RESTful API with FastAPI

No preview available for this content.

Aug 04, 2024
Read More
Code
javascript json

JavaScript Code Snippet: Fetch and Display Data from an API

No preview available for this content.

Aug 04, 2024
Read More
Code
javascript

Fetch JSON Data from API in JavaScript

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!