RESTful APIs
RESTful APIs
RestFull_API
Rest stands for Representational State Transfer.
Let's understand the meaning of each word in the REST acronym.
State means data Representational means formats (such as XML, JSON, YAML,
HTML, etc) Transfer means carry data between consumer and provider using the
HTTP protocol
Status Codes
APIs use HTTP status codes to indicate the result of a request:
200s: Success (200 OK, 201 Created)
300s: Redirection
400s: Client errors (404 Not Found, 400 Bad Request)
500s: Server errors
Example RESTful API Endpoints
For a hypothetical e-commerce system:
GET /products - List all products
GET /products/123 - Get details for product with ID 123
POST /products - Create a new product
PUT /products/123 - Update product 123
DELETE /products/123 - Delete product 123
1. HTTP Methods
HTTP (Hypertext Transfer Protocol) is a protocol that allows communication
between clients and servers on the World Wide Web. There exist several dozen
different HTTP Methods that can be used for different purposes. The main 9 most
popular HTTP Methods are explained below.
1. GET Request
The GET request is one of the HTTP methods which in simple words is in charge
of grabbing data from a data source. The response from a GET request can
contain data such as a list of items, a single item, or even just a status message.
A GET request is a safe and idempotent method, meaning that it can be repeated
multiple times without having any side effects because it should only retrieve
data, not modify it.
2. POST Request
The POST request is used to send data to the server from a client to create a new
resource. The data which is sent as part of a POST request is encoded in the
body of the request and is not visible in the URL, unlike with a GET request.
3. PUT Request
With help of the PUT request, you can update an existing resource. One
important thing to keep in mind when you are updating an existing resource via
PUT request is that the request body of a PUT request - - -- should contain a
complete representation of the resource. Even if you want to update one of the
several fields of an existing resource, you need to provide a complete
representation of the resource and pass it as a request body. Otherwise, the
missing fields will be set to NULL, or in some other cases, the request just would
fail. If you want to do a partial update of a resource, look at the PATCH HTTP
method.
4. DELETE Request
The DELETE request can be used when you want to delete an existing resource
from the server. Usually, you specify a resource that you want to delete by
providing an ID of a resource as part of the URL parameter.
5. PATCH Request
Similar to a PUT HTTP request, a PATCH request can be used to update an
existing resource. However, the difference between PUT and PATCH is that when
sending a PUT request, the body of a request should contain a complete
representation of the resource but with a PATCH request you can provide a partial
representation of the resource.
6. HEAD Request
HTTP HEAD method is used to fetch the request headers that would be returned
if a corresponding GET request was made. In other words, the HEAD method is
the same as the GET method with the only difference being that it doesn't return
the response body when the request was made.
The HEAD method can be very useful because it can save you some bandwidth
in situations when you only need to retrieve some metadata about the resource
without retrieving the actual resource as part of the response body. The
metadata returned by a HEAD request can be used to validate the information
about the resource such as Content-Length of the resource, Content-Type, Last-
Modified date, etc.
7. TRACE Request
HTTP TRACE request can be used for debugging purposes when you want to
determine what is exactly happening with your HTTP requests. When the TRACE
request is sent, the web server would normally echo the exact content of an
HTTP request back to the client.
However, the TRACE requests should not be enabled in a production environment
because in some scenarios they potentially can reveal some sensitive
information about the server.
8. CONNECT Request
HTTP CONNECT request method can be used in order to establish a network
connection between a client and a server to create a secure tunnel. Once the
connection is established, the client and server can - communicate with each
other directly and forward data packets to each other.
9. OPTIONS Request
HTTP OPTIONS request method can be used to request the available
communication options from the server for the target resource.
When a client sends an OPTIONS request to a server, the server would normally
include the list of the allowed HTTP methods for the target resource as part of
the "Allow" header in the response.
Features of REST Overview
1.Uniform Interface
A logical URI system with uniform ways to fetch and manipulate data is what
makes REST easy to work with.
In REST architecture, there is the concept of safe and idempotent methods.
Safe methods are the ones that do not modify resources. An example include
GET and HEAD.
An idempotent method is a method that produces the same results no matter
how many times is executed. These are GET, PUT and DELETE.
2 . Representations
Restful services focus on resources and providing access to the resources.
A resource can be easily thought of as an object in OOP.
This is the first thing to do while designing RESTful services is identifying
different resources and determining the relation between them.
Once the resources are identified, the representation is the next course of action
Unlike SOAP which restricts us to use XML to represent the data, with REST we
can use JSON or XML.
Usually, JSON is the preferred method for representing the resources to be called
by mobile or web clients, But XML can be used to represent more complex
resources.
3. Messages
The client and the server talk to each other via messages in which the cleint sends a message to the
server which is often called a request and the server sends back a response
Apart from the actual data exchanged between the client and the server in the form of request and
response body, there are some metadata exchanged by the client and the server in the form of
request and response headers.
5. Caching
Caching is a technique that stores a copy of a given resource, and serves it back when requested
saving database calls and processing time. Caching can be configured to cache data in minutes,
hours, and days, whereby after the configured time expires the cached data gets deleted.
It can be done at different levels, like the client, the server, or a middleware proxy server.
Caching in REST API is controlled using HTTP headers.
6. Stateless
Each request from the client to the server must contain all the information necessary for the server
to understand the request and cannot take advantage of any stored context on the server. Session
state is therefore kept entirely on the client
Statelessness here means that every HTTP response is a complete entity in itself
and enough to serve the purpose of providing information to be executed without
any need for another HTTP request.
API DESIGN
1.Long-term Implementation This helps you analyze the flaws in design before
actual implementation. This helps the developers to choose the right kind of
platforms and tools to build upon making sure the same system can be scaled for
more users later.
2. Spec-Driven Development
This enforces API design using definition, and not just the code, which ensures
that the changes are made to the codebase while API design is intact.
3. Prototyping
Once the API specs are put in place, prototyping helps you visualize the API
before actual development by letting the developers create mock API to help
them understand every potential aspect of the API
5. SQL Databases
SQL databases use SQL for data manipulation and definition.
SQL systems work great when the data in use needs to be relational and the
schema is predefined.
SQL databases store data in forms of the tables made up of rows and columns
and vertically scalable.
6. NoSQL Databases
have a dynamic schema for unstructured data and store data in different ways
ranging from column-based(Apache Cassandra), document-based(MongoDB),
graph-based(Neo4j), or as a key-value store (Redis).
This provides the flexibility to store data without a predefined structure and
versatility to add fields to the data structure on the go.
Being schemaless is the key distinction of NoSQL databases, and it also makes
them better suited for distributed systems.
Here Is The Small Example Then You will understand This
Example 1
Example1:
class HelloWorld(Resource):
def get(self):
return {"message": "Hello, World!"}
api.add_resource(HelloWorld, '/hello')
if __name__ == '__main__':
app.run(debug=True)
Example2:
Example 2
from flask import Flask, jsonify
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
app = Flask(__name__)
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)
if __name__ == '__main__':
app.run(debug=True)
Square Operation
CRUD operations
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
app = Flask(__name__)
api = Api(app)
class UserSchema(Schema):
username = fields.Str(required=True)
email = fields.Email(required=True)
class UserResource(Resource):
def get(self):
# Implement logic to retrieve and return user data
# For demonstration, let's return dummy data
users = [
{"username": "user1", "email": "[email protected]"},
{"username": "user2", "email": "[email protected]"}
]
return users, 200
def post(self):
# Get user data from form parameters or request JSON
json_data = request.get_json()
username = json_data.get('username')
email = json_data.get('email')
try:
# Validate user data
user_data = UserSchema().load({"username": username, "email": email})
except ValidationError as err:
# Handle validation errors
return {"message": "Validation error", "errors": err.messages}, 400
# Process valid data (in this example, just return the data)
return user_data, 201
api.add_resource(UserResource, '/user')
if __name__ == '__main__':
app.run(debug=True)