1. Introduction
Hello! We are a writer team from Definer Inc.
In this issue, you are wondering how to develop a Restful API with Python and Flask.
Let's take a look at the actual screens and resources to explain in detail.
2. Purpose/Use Cases
This article summarizes information and practices that can be helpful when you want to create a Restful API in Flask.
3. What is Restful API?
First, let's review the Restful APIs.
A Representational State Transfer (RESTful) API is a type of web API that follows the principles and constraints of the REST architectural style. REST is an architectural pattern commonly used for designing networked applications and systems, especially for web services. It provides a standard way for different software applications to communicate and interact over the internet.
Restful AP is an API that satisfies the following
- Statelessness: RESTful APIs are stateless, meaning that each request from a client to the server must contain all the information necessary to understand and process that request. The server does not retain any session state between requests, enhancing scalability and simplicity.
- Resource-Based: REST treats everything as a resource, which can be an object, data, or service. Each resource is uniquely identifiable through a URL (Uniform Resource Locator), and clients interact with these resources using standard HTTP methods (GET, POST, PUT, DELETE) to perform specific actions.
- Uniform Interface: RESTful APIs use a uniform and consistent set of standardized methods, status codes, and media types (e.g., JSON, XML) for communication. This consistency simplifies client-server interactions and promotes interoperability.
- Client-Server Architecture: REST separates the client (the user interface or application) from the server (the data and business logic). This division of responsibilities allows each component to evolve independently, enhancing scalability and flexibility.
- Stateless Communication: Each request from the client to the server must include all the required information, including authentication details, as no client context is stored on the server. This design makes RESTful APIs easy to scale and cache.
- Cacheability: Responses from RESTful APIs can be explicitly marked as cacheable or non-cacheable, improving performance and reducing the need for redundant requests.
- Layered System: REST allows for a layered architecture, where multiple components can interact with each other via well-defined interfaces. This enhances the system's flexibility and maintainability.
- Use Nouns to Represent Resources: Represent resources (objects, data, or services) as nouns in the API's URLs. For example,
/users
,/products
, or/orders
. - Use HTTP Methods: Utilize the appropriate HTTP methods to perform actions on resources:
- GET: Retrieve a resource or a collection of resources.
- POST: Create a new resource.
- PUT: Update an existing resource (use for complete updates).
- PATCH: Update a part of an existing resource.
- DELETE: Delete a resource.
- Use Plural Nouns for Resource Collections: Use plural nouns in the URL for resource collections to make it more intuitive. For example,
/users
instead of/user
. - Use Specific Names for Resources: Use specific names rather than generic ones. For example,
/products
is preferred over/items
. - Use Proper HTTP Status Codes: Use appropriate HTTP status codes in responses to indicate the status of the request:
- 200 OK: Successful GET or PUT request.
- 201 Created: Successful POST request that resulted in resource creation.
- 204 No Content: Successful DELETE request.
- 400 Bad Request: Invalid request or missing parameters.
- 401 Unauthorized: Authentication failure.
- 404 Not Found: Resource not found.
- 500 Internal Server Error: Server-side error occurred.
- Versioning: Consider versioning your API to allow backward compatibility with older clients as your API evolves. You can include the version number in the URL or as a request header.
- Use Proper Pagination: For large collections, implement pagination to limit the number of results returned in a single response. Use query parameters like
?page=1&limit=10
. - Proper Use of HTTP Headers: Use HTTP headers appropriately for caching, content negotiation (e.g., specifying JSON or XML response), and authentication (e.g., using JWT tokens).
- Use HATEOAS (Hypermedia as the Engine of Application State): Include hypermedia links in the API responses to allow clients to navigate the API easily. This enhances the discoverability of resources and reduces coupling between clients and the API.
- Security Considerations: Implement proper security mechanisms like HTTPS, authentication, and authorization to protect sensitive data and resources.
- Consistency in Naming Conventions: Follow a consistent naming convention for URLs, parameters, and response structures to make the API more predictable and easier to understand.
- Error Handling: Provide informative error messages in responses to help developers understand issues with their requests.
4. FlaskAPI Introduction
Flask-API, commonly known as Flask, is a lightweight and versatile web framework for building RESTful APIs and web applications in Python. As a microframework, Flask prioritizes simplicity and minimalism, making it easy for developers to create APIs quickly and efficiently. Its straightforward routing system enables developers to map URLs to specific functions, facilitating the definition of API endpoints and their corresponding behaviors. With support for standard HTTP methods, Flask allows the creation of RESTful APIs with ease.
Flask incorporates the popular Jinja2 templating engine, enabling the creation of dynamic HTML templates for rendering web pages with data from the backend. The framework's solid foundation is built on top of the Werkzeug WSGI toolkit, ensuring efficient handling of requests and responses. Additionally, Flask boasts a vibrant ecosystem of extensions and add-ons, enhancing its functionality and enabling developers to integrate features like authentication, database integration, and form handling.
5. AWS SAM Introduction
AWS SAM (Serverless Application Model) is an open-source framework provided by Amazon Web Services (AWS) that simplifies the development and deployment of serverless applications on the AWS Cloud. It extends the capabilities of AWS CloudFormation, AWS's infrastructure-as-code service, to support the definition and management of serverless resources.
Key features and components of AWS SAM include:
- Infrastructure as Code (IaC)
- Serverless Application Model Templates
- Local Testing and Debugging
- Lambda Function Packaging
- API Gateway Integration
- Event Sources
- Seamless Deployment
- Integration with AWS Services
6. Preparation of configuration files
First, we will set up the Lambda setup.
Prepare the AWS SAM configuration file needed to create the Lambda function.
(1) Prepare configuration files
Prepare template.yaml as follows:
## template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Globals:
Function:
Timeout: 10
Resources:
TestFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: "test"
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Events:
HelloWorldApiEvent:
Type: Api
Properties:
Path: /hello
Method: get
CreateUserApiEvent:
Type: Api
Properties:
Path: /users
Method: post
GetUserApiEvent:
Type: Api
Properties:
Path: /users/{user_id}
Method: get
UpdateUserApiEvent:
Type: Api
Properties:
Path: /users/{user_id}
Method: put
DeleteUserApiEvent:
Type: Api
Properties:
Path: /users/{user_id}
Method: delete
Overall, this SAM configuration file defines a serverless application with a Lambda function named "TestFunction" and API Gateway resources necessary to deploy the application, along with the respective CRUD paths and their associated event triggers. When the API Gateway receives requests at these endpoints, it triggers the "TestFunction" Lambda function to execute, allowing developers to build a serverless API with ease.
In requirements.txt, add the following three lines:
It means three Python packages we have to install for our app.
In requirements.txt, add the following three lines:
It means three Python packages we have to install for our app.
requests
Flask
aws-wsgi
7. Lambda Implementation
Next, we will implement Lambda.
(1) Preparation of Lambda sample code
Copy and paste the following code into app.py:
import awsgi
from flask import Flask, request, render_template
app = Flask(__name__)
# Create (POST) a new resource
@app.route('/users', methods=['POST'])
def create_user():
return {'msg': 'created user'}
# Read (GET) a specific resource
@app.route('/users/<user_id>', methods=['GET'])
def get_user(user_id):
return {'msg': 'get user'}
# Update (PUT) an existing resource
@app.route('/users/<user_id>', methods=['PUT'])
def update_user(user_id):
return {'msg': 'updated user'}
# Delete (DELETE) an existing resource
@app.route('/users/<user_id>', methods=['DELETE'])
def delete_user(user_id):
return {'msg': 'deleted user'}
# Sample Route
@app.route('/hello', methods=['GET'])
def hello_get():
return {'msg': 'hello world'}
def lambda_handler(event, context):
return awsgi.response(app, event, context)
This Python code sets up a simple Flask app with one API endpoint (
(2) Deploying Lambda
Deploy Lambda using the "sam build" and "sam deploy" commands.
(3) Testing the API
Note the API endpoint URL and make an API call using the Curl command.
The response comes back as expected!
/hello
) that responds with a "Hello World" message when accessed via a GET request and a simple RESTful API with CRUD (Create, Read, Update, Delete) operations for a resource called "users". The Lambda handler function (lambda_handler
) acts as the entry point for AWS Lambda and integrates the Flask app with the AWS Lambda environment using the awsgi
library, allowing it to handle API Gateway events.(2) Deploying Lambda
Deploy Lambda using the "sam build" and "sam deploy" commands.
(3) Testing the API
Note the API endpoint URL and make an API call using the Curl command.
The response comes back as expected!
## ビルド
sam build
## deploy
sam deploy --guided
## API Testing
curl -X GET https:/${API Endpoint URL}/${Stage name}/hello
## Test Results
{"msg":"hello world"}
8. Cited/Referenced Articles
Troubleshooting API Gateway HTTP 504 Timeout Errors ...
Troubleshooting HTTP 403 errors from API Gateway
Developing a RESTful API with Python and Flask
Developing a RESTful API with Flask - Japanese garbled in jsonify ...
Reference articles on developing APIs with Python's Flask | iret.media
Python Flask API Development - Qiita
[Python] Using decorators | Engineer as much as you play
9. About the proprietary solution "PrismScaler"
・PrismScaler is a web service that enables the construction of multi-cloud infrastructures such as AWS, Azure, and GCP in just three steps, without requiring development and operation.
・PrismScaler is a web service that enables multi-cloud infrastructure construction such as AWS, Azure, GCP, etc. in just 3 steps without development and operation.
・The solution is designed for a wide range of usage scenarios such as cloud infrastructure construction/cloud migration, cloud maintenance and operation, and cost optimization, and can easily realize more than several hundred high-quality general-purpose cloud infrastructures by appropriately combining IaaS and PaaS.
10. Contact us
This article provides useful introductory information free of charge. For consultation and inquiries, please contact "Definer Inc".
11. Regarding Definer
・Definer Inc. provides one-stop solutions from upstream to downstream of IT.
・We are committed to providing integrated support for advanced IT technologies such as AI and cloud IT infrastructure, from consulting to requirement definition/design development/implementation, and maintenance and operation.
・We are committed to providing integrated support for advanced IT technologies such as AI and cloud IT infrastructure, from consulting to requirement definition, design development, implementation, maintenance, and operation.
・PrismScaler is a high-quality, rapid, "auto-configuration," "auto-monitoring," "problem detection," and "configuration visualization" for multi-cloud/IT infrastructure such as AWS, Azure, and GCP.