Skip to content

REST

Overview

REST (or REpresentational State Transfer) is an architectural style first described in Roy Fielding's Ph.D. dissertation on Architectural Styles and the Design of Network-based Software Architectures.


https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#introduction

API Introduction

An API is a set of programming code that enables data transmission between one software product and another. It also contains the terms of this data exchange.

How API Work

Ref: What is an API?

CRUD: CRUD stands for Create, Read, Update and Delete.

C - Create (Post) R - Read (Get) U - Update (Put) D - Delete (Delete)

Introduction about schema

https://www.altexsoft.com/blog/soap-vs-rest-vs-graphql-vs-rpc/

HTTP Methods

The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently.

Below is a table summarizing the methods used by this service API.

HTTP VERB

CRUD

DESCRIPTION

POST

CREATE

Used to create new resources

NOT SAFE - NOT IDEMPOTENT

Making two identical POST will duplicate the resource

GET

READ

Retrieve a representation of a resource

SAFE - IDEMPOTENT

Multiple identical requests return the same result

PUT

UPDATE

Update or Create a resource

NOT SAFE - IDEMPOTENT

Multiple identical requests will update the same resource

DELETE

DELETE

Used to delete a resource

NOT SAFE - IDEMPOTENT §

Multiple identical requests will delete same resource

§

Calling DELETE on a resource a second time will often return a 404 (NOT FOUND) since it was already removed and therefore is no longer findable. This, by some opinions, makes DELETE operations no longer idempotent, however, the end-state of the resource is the same. Returning a 404 is acceptable and communicates accurately the status of the call.

IDEMPOTENCE

Clients can make that same call repeatedly while producing the same result.

In other words, making multiple identical requests has the same effect as making a single request. Note that while idempotent operations produce the same result on the server (no side effects), the response itself may not be the same (e.g. a resource's state may change between requests).

https://www.contrive.mobi/aviorapi/HTTPMETHODS.html

HTTP Methods

This has been captured at MDN HTTP Method

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.

Method Descriptions
GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
HEAD The HEAD method asks for a response identical to a GET request, but without the response body.
POST The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server.
PUT The PUT method replaces all current representations of the target resource with the request payload.
DELETE The DELETE method deletes the specified resource.
CONNECT The CONNECT method establishes a tunnel to the server identified by the target resource.
OPTIONS The OPTIONS method describes the communication options for the target resource.
TRACE The TRACE method performs a message loop-back test along the path to the target resource.
PATCH The PATCH method applies partial modifications to a resource.

Ref: HTTP request methods

Design an API

This design go to basic protocol to create an API endpoint from the scrath

Following topics are required to build, develop this project

[1] API: Introduction, Why, How

[2] What information are required to gather before you develop? With and without Business Analyst?

[3] API Concentps from VEEAM: VEEAM REST Methods

[4] API HTTPs methods

Method Description
GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data
HEAD The HEAD method asks for a response identical to a GET request, but without the response body
POST The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server
PUT The PUT method replaces all current representations of the target resource with the request payload
DELETE The DELETE method deletes the specified resource
CONNECT The CONNECT method establishes a tunnel to the server identified by the target resource
OPTIONS The OPTIONS method describes the communication options for the target resource
TRACE The TRACE method performs a message loop-back test along the path to the target resource
PATCH The PATCH method applies partial modifications to a resource

[5] HTTPs methods progress

a) For GET

  • Arguments Parsing

  • Validate Elements

  • Construct DML Query

  • Returned response

b) For POST | PUT

  • Arguments Parsing

  • Validate Elements

[1] Check coi có exists True/False Routes [2] Fetching data {current} Routes [3] User update requirement {mapping-change} Routes [4] Update components CRUD

  • Construct DML Query

  • Returned response

c) For DELETE

  • Arguments Parsing

  • Validate Elements

  • Construct DML Query

  • Returned response

[5] Design Response Output:

a) For GET

List of Base Metadata

b) For POST | PUT

Returned body of item

c) For DELETE

Status of events

[Progress] When update new schema for model

make down-refresh
make up-refresh
docker exec -it backend-pluto python3 scripts/gen_db.py

For Testing

Test always is a part of developer when create featute follow to TDD progress.

FastAPI intergrate testing with pytest, httpx and some fake data generate tools like Faker

ref: FastAPI Testing

ref: Faker to create fake data

ref: Factoy Boy

Progress

Export the variable TEST_DATABASE_URI that is the connection string to Test Database. The database for testing purpose can be the database service in local development database in Docker.

export TEST_DATABASE_URI=postgresql+pg8000://postgres:postgres@127.0.0.1:5432/postgres

Prepair working directory and the environment

cd backend && source venv/Scripts/activate

then write your tests cases, with syntax of prefix test_*

then, execute the test

python3 -m pytest

https://labs.flinters.vn/technote/thiet-ke-restful-api-nhu-the-nao/

Concept of Fixture of Pytest

ref: https://docs.pytest.org/en/6.2.x/fixture.html

Useful Documents

Database

The project rely on the ORM class mapping, which worked with sqlalchemy

Useful with sqlalchemy-utils

Status Codes

Q: How do you know when to yield status code, and which codes should be returned?

A: The status code when you finish a task from requests from users, or when hit any errors.

The status code must be meaningful, because its used by another systems.

The status codes from MDN documents are useful:

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

[+] Informational responses (100 – 199)

[+] Successful responses (200 – 299)

[+] Redirection messages (300 – 399)

[+] Client error responses (400 – 499)

[+] Server error responses (500 – 599)

For more detail: HTTP response status codes

The FastAPI has supported this too, read through Response Status Code

Troubleshooting

[1] Align database models to CRUD operations arguments

[2] The output results

Some errors that developers usually create:

[1] Unboundlocalerror

Read: https://linuxhint.com/python-unboundlocalerror/

[2] Missing the packages that required in requirements.txt

[3] Should import <module> or from <module> import x,y,z

It's depends, but when import, Python will know to cached the moduled has loaded.

It's based on timimg for import, which lead to initation time (import time) is larger.

It's based on the way of reminders, occurs when we not familars with the module.

[4] Naming for functions, objects, modules

Should read: .NET Framework naming guidances

a) For objects: use upper case with _. E.g: REQUIRED_COLUMNS instead of RequiredColumns

b) For class: use Camel syntax. E.g: ResponseAdjustment

c) For function: use snake syntax. E.g: def get_element

Its should align with prefix for module.

[5] Missing type hint and documents for usages.

Implement

https://dev.mysql.com/doc/refman/8.0/en/error-log-event-fields.html

Core Error Event Fields These error event fields are core fields:

time

The event timestamp, with microsecond precision.

msg

The event message string.

prio

The event priority, to indicate a system, error, warning, or note/information event. This field corresponds to severity in syslog. The following table shows the possible priority levels.

Event Type Numeric Priority System event 0 Error event 1 Warning event 2 Note/information event 3 The prio value is numeric. Related to it, an error event may also include an optional label field representing the priority as a string. For example, an event with a prio value of 2 may have a label value of 'Warning'.

Filter components may include or drop error events based on priority, except that system events are mandatory and cannot be dropped.

In general, message priorities are determined as follows:

Is the situation or event actionable?

Yes: Is the situation or event ignorable?

Yes: Priority is warning.

No: Priority is error.

No: Is the situation or event mandatory?

Yes: Priority is system.

No: Priority is note/information.

err_code

The event error code, as a number (for example, 1022).

err_symbol

The event error symbol, as a string (for example, 'ER_DUP_KEY').

SQL_state

The event SQLSTATE value, as a string (for example, '23000').

subsystem

The subsystem in which the event occurred. Possible values are InnoDB (the InnoDB storage engine), Repl (the replication subsystem), Server (otherwise).

Optional Error Event Fields Optional error event fields fall into the following categories:

Additional information about the error, such as the error signaled by the operating system or the error label:

OS_errno

The operating system error number.

OS_errmsg

The operating system error message.

label

The label corresponding to the prio value, as a string.

Identification of the client for which the event occurred:

user

The client user.

host

The client host.

thread

The ID of the thread within mysqld responsible for producing the error event. This ID indicates which part of the server produced the event, and is consistent with general query log and slow query log messages, which include the connection thread ID.

query_id

The query ID.

Debugging information:

source_file

The source file in which the event occurred, without any leading path.

source_line

The line within the source file at which the event occurred.

function

The function in which the event occurred.

component

The component or plugin in which the event occurred.

Reference

https://www.contrive.mobi/aviorapi/HTTPMETHODS.html