This project demonstrates how to create a RESTful API using Flask (Python web framework) and TypeScript (JavaScript with static typing). The goal of this README is to guide you through the steps of setting up, running, and understanding the project architecture.
The combination of Flask on the backend and TypeScript on the frontend or server side allows for efficient and scalable applications, leveraging the strengths of both technologies: Flask for simplicity and flexibility and TypeScript for type safety and better development experience.
To work on this project, you will need the following dependencies installed on your machine:
pip install Flask
pip install Flask-CORS
(to handle CORS issues when integrating frontend)pip install Flask-RESTful
(for RESTful routing)npm install -g typescript
npm install -g ts-node
(for running TypeScript files without pre-compiling)Below is the project structure:
restfulapi-and-flask/
│
├── backend/ # Backend code written in Flask
│ ├── app.py # Main Flask application file
│ ├── models.py # Defines the data models
│ ├── routes.py # Contains the API endpoints
│ ├── requirements.txt # Python dependencies
│ └── tests.py # Unit tests for the backend API
│
├── frontend/ # Frontend or service layer written in TypeScript
│ ├── tsconfig.json # TypeScript configuration
│ ├── src/
│ ├── index.ts # Entry point for TypeScript code
│ └── apiClient.ts # TypeScript client that makes API calls
│
└── README.md # Project README file (this file)
Follow the instructions to set up and run the project.
git clone https://github.com/your-username/restfulapi-and-flask.git
cd restfulapi-and-flask
cd backend
pip install -r requirements.txt
app.py
: The main entry point for the Flask API.routes.py
: Defines the API routes (GET, POST, PUT, DELETE).models.py
: Manages the application’s data models (e.g., users, tasks).export FLASK_APP=app
flask run
The server will start on http://127.0.0.1:5000/
.
cd ../frontend
npm install
The tsconfig.json file is already included in the project. It sets up the TypeScript compiler options, such as ES6 modules and strict type checking.
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
To compile and run the TypeScript files, use ts-node
:
npx ts-node src/index.ts
Once the Flask server is running, and the TypeScript client is set up, you can interact with the API through the TypeScript client or Postman/cURL.
http://127.0.0.1:5000/
Here are some of the sample RESTful API endpoints defined in routes.py:
GET /api/items
: Fetch all itemsGET /api/items/<id>
: Fetch a specific item by IDPOST /api/items
: Create a new itemPUT /api/items/<id>
: Update an existing item by IDDELETE /api/items/<id>
: Delete an item by IDYou can test these endpoints using Postman or cURL.
Example:
curl http://127.0.0.1:5000/api/items
app.py
(Backend)from flask import Flask
from flask_cors import CORS
from routes import api
app = Flask(__name__)
CORS(app) # Enable Cross-Origin Resource Sharing
api.init_app(app)
if __name__ == "__main__":
app.run(debug=True)
routes.py
.routes.py
This file contains the API routes:
from flask_restful import Api, Resource
api = Api()
class Item(Resource):
def get(self, item_id):
return {"item_id": item_id}
api.add_resource(Item, '/api/items/<int:item_id>')
apiClient.ts
(Frontend)import axios from 'axios';
const BASE_URL = "http://127.0.0.1:5000";
export const getItems = async () => {
try {
const response = await axios.get(`${BASE_URL}/api/items`);
console.log(response.data);
} catch (error) {
console.error("Error fetching items", error);
}
};
This file uses Axios to make HTTP requests from the TypeScript frontend to the Flask API.
You can test the API using the following methods:
Unit Testing (Flask Backend):
Write unit tests in tests.py
to verify the functionality of your Flask routes.
Postman / cURL: Use these tools to manually send HTTP requests to the Flask API and verify the responses.
FLASK_ENV
, DATABASE_URL
, etc.tsc
Contributions are welcome! Please fork this repository and submit a pull request.
This project provides a basic foundation for building a full-stack application using Flask (backend) and TypeScript (frontend). Feel free to extend it by adding more routes, authentication, database integrations, and more!