Writing a web API to your system

    Good afternoon,% username%!
    Over the past year, I have faced several tasks of writing a SOAP / REST API for various services and have come up with a more or less convenient model. I do not pretend to be a fundamental study, I just want to share the experience of stepping on a rake.

    First, the general requirements for the default API:
    • expandability
    • convenient standardized request format
    • convenient standardized response format
    • adequate security
    • return query execution errors


    The client of our API can be either a server (PHP / Perl / Python etc) or a UI (JS). The authorization mechanisms will be somewhat different, but everything else is better to standardize.
    After much testing in real life, I preferred JSON. I have nothing against XML, but very often I have to use the API functionality from JavaScript - why not use the native format?

    The structure of the server request looks something like this: In order: cmd is a limited set of commands that provides functionality. For example, auth, profile, edit, view, and so on - depending on your needs. This parameter is not passed in JSON, so as not to parse JSON in the absence of such a command. data - the transmitted information in JSON.
    cmd="имя команды"&data="JSON объект"&sig="сигнатура запроса, используемая для аутентификации и проверки целостности запроса"



    sig is a signature that provides validation of the request and authorization. For example, when querying server-server, I use the following algorithm: md5 (cmd + secret + data), where secret is information known to both servers (both ours and the client server), but unknown to anyone else.
    When requesting a server-client (AJAX-JavaScript), you have to use a less secure option - secret is stored in a cookie and each session is changed.

    Answer: I think no explanation is needed here. We are approaching the implementation. Consider the algorithm of the server side:
    {
    status: "ok или error - удачность выполнения запроса"
    response: "возвращаемые данные"
    error: "код ошибки или 0 в случае удачи"
    }



    1. check if command matching cmd parameter exists
    2. if so, then check the signature (sig) - at this stage we eliminate most of the inept attacks, not yet loading the server
    3. load the appropriate module that implements the functionality and transfer data to it
    4. the module does its job - he doesn’t need us here
    5. generate an answer with the results of the module or an error code and return it to the client

    I love OOP, but not all developers who write modules for the systems I develop are also fond of it. Therefore, the code can be anything, the main thing is that it returns a result.

    Let's look at the classes that have been formed for several similar systems and now migrate from one to another:
    1. Manager - checks the existence of the command and the signature is correct, checks the correctness of the input data and sends errors about incorrect data
    2. Module - each object of this class describes a specific module. The description consists of a name, a list of files necessary for operation, which will be included when the module starts, a list of parameters that it will take from the Registry object, a list of parameters without which it does not start, and immediately give an error
    3. Registry - singleton, in honor of the template of the same name - wraps incoming data under the strict guidance of the Manager object. Later it will be accessed by the modules for data.
    4. Response - singleton, builds a response from the data received from the module. It is in it that we encode the response in the format we need (JSON in this case)
    5. DB wrapper class to taste

    Thus, modules can be written at least procedurally - they take all the data from the Registry object and return it to the Response object.

    Standard modules that are found in almost every system:
    • auth - open connection with API
    • log_out - actually closing the connection
    • user - display user information
    • view - view one record
    • list - view a list of records
    • add - add record
    • edit - edit record
    • del - delete a record

    The total number of modules in the system does not affect its performance, so the flight of your imagination in the field of functionality is not limited.

    If the topic of API development is interesting to the habrasociety, I can prepare an article with an example of implementation and source codes. Hope the above information helps in designing your system.

    UPD : this is not a description of creating REST or God forbid a SOAP API. This is what resulted in the operation of several systems and is a more productive and simple solution. If you need book REST - read Frauler, everything is described there without me.

    Also popular now: