top of page
Search

REST API - Lesson 1

Objective: We learn by doing. So, we will create an API end-point which will read a flat-file located in my machine.


There are 3 components here to start with:

  1. Data Source

  2. Server

  3. API endpoints


Most often learners switch to #3 as it is easy to start with. But, we will start from the basics. What are we trying to achieve: Create a REST API endpoint for a dataset.


  1. Data Source: let us go with a simple .csv file.

    ree

    A simple .csv file from GitHub. You can use your own data.


  2. Server:

    I will use my own machine as the hardware to host the server here. We will discuss about industrialization in the advanced concepts section. We are not focusing on security, caching, concurrency, distributed processing and other such concepts in this article. I will definitely cover them in later sections.


  1. API Endpoints:

    Now, comes the fun part. To understand this better let us take a look at an example:


Component

Example

Description

Protocol

https

The secure communication protocol used for the request. HTTP (Hypertext Transfer Protocol) is the foundation of REST, and HTTPS (HTTP Secure) is the standard for secure data transfer.

Subdomain

api

A prefix indicating this is the API entry point, often used to separate the API service from the main website.

Domain Name

The registered name of the web server or service provider.

Port

(Implied 443)

The port number used for the connection. For HTTPS, port 443 is the standard and is usually omitted.

Base Path / Version

/v1

The starting point of the API, often including a version number (v1) to allow for future changes without breaking older client applications.

Resource

/users

The primary resource collection being addressed. REST uses nouns (usually plural) to represent data objects.

Resource Identifier

/42

A unique identifier for a specific instance of the resource. This segment tells the server which user to target.

Path / Endpoint

/v1/users/42

The complete path after the domain name, defining the entire location of the targeted resource.

Looks complicated? Don't worry, let us dive deeper.


ree

So we need a software program that will give us an API end-point to access this file in this machine. There are quite a handful of programming languages and frameworks (i.e. standardized libraries, modules, functions) to achieve this.


My preferred programming language is Python but you can extrapolate this to your favorite programming languages too. Our focus in this article is to develop a simple API end-point and not the programming language or the frameworks that we use. Later in the upcoming articles as we dive deeper into the fundamentals of REST API we will focus more on the frameworks and their use. Also in the advanced sections we will explore the same concepts using no-code or low-code tools as well.


This is the code:

from flask import Flask, jsonify

import pandas as pd


# The name of your CSV file

CSV_FILE_PATH = '/home/seaking/Projects/API/customers-100.csv'


# Initialize the Flask application

app = Flask(__name__)



# --- API Endpoint ---

@app.route('/api/data', methods=['GET'])

def get_csv_data():

"""

Reads the CSV file and returns the data as a JSON list of dictionaries.

"""

try:

# Read the CSV file into a pandas DataFrame

df = pd.read_csv(CSV_FILE_PATH)


# Convert the DataFrame to a list of records (JSON format)

# 'records' format: [{column -> value}, ... {column -> value}]

data = df.to_dict(orient='records')


# Return the data as a JSON response

return jsonify(data)


except FileNotFoundError:

# Handle the case where the CSV file does not exist

return jsonify({"error": f"The file {CSV_FILE_PATH} was not found."}), 404

except Exception as e:

# Handle any other exceptions

return jsonify({"error": f"An error occurred: {str(e)}"}), 500



# --- Running the Server ---

if __name__ == '__main__':

# 'debug=True' is good for development, but remove for production

app.run(debug=True)

# The API will be available at http://127.0.0.1:5000/api/data

Let me break this down:

  1. Libraries and variables

  2. Server Initialization

  3. Function to Read Data

  4. Routing - connect API call to function call #3.

  5. Error handling in #3.


This is just the programming part. Let us look at the program in execution and then come back for more analysis.

ree

I saved the above Python code as 'API-1.py'; now let us execute this code:

ree

So now the server is up and running. Let us navigate to a browser and check the output:

ree

Viola. The .csv file from my laptop is now available via an API call. But, wait - how did we get to this IP-Port combination?


When I ran my Flask application using app.run(debug=True) without any arguments, it defaults to:


IP Address: 127.0.0.1 (or localhost)

Port Number: 5000


This is why we see the message: Running on http://127.0.0.1:5000


  1. IP Address (127.0.0.1)

The IP address 127.0.0.1 is the standard loopback address or localhost.


Loopback: This address ensures that the server is only accessible from your own computer. Any requests made to this address start and end on the same machine (they "loop back"). This is the safest default for development because it doesn't expose the running application to the wider network.


  1. Port Number (5000)

Port 5000 is simply a common, non-privileged port chosen by Flask's underlying development server (Werkzeug).


Non-Privileged: Ports below 1024 (like 80 for HTTP or 443 for HTTPS) are considered "well-known" and require administrator or root privileges to use. Port 5000 is well above this range, meaning it can be used by any user without special permissions.


Hope you all learnt something new. Now, did you notice the 'path or base-path or resource'? How did we know we have to navigate to /api/data ?

ree

This line specifies the path and the method.


Method? What is a method? Stay tuned. We will discuss more on this in the next post.



 
 
 

Comments


I Sometimes Send Newsletters

Thanks for submitting!

bottom of page