API REST — Tutorial. Hi, all!
By: Anderson Henrique
Tags: Golang, Rest, Rest Api, It, Technology

Hi, all!

Here is a brief tutorial about REST Architecture to facilitate the execution and bring up your web services’ flexibility.

We will create a rest server based on a registry. REST -Representational State Transfer — has fundamental characteristics for web application development; it is a set of principles and definitions needed to create a project with well-defined interfaces. One of REST’s fundamental principles is to separate the API into semantic resources, which will be managing through HTTP requests, and they should make sense to the users of the API. Also, there is the CRUD, which is an application that contains the “registration screens.” These abbreviations represent the services “create”, “read”, “update” and “delete”, respectively. Therefore, the CRUD system is a direct link to the operations and not to the system itself. In the tutorial, we will use GET, POST, PUT, and DELETE, which have the same functions as CRUD.

In this first step, you need to open your VS CODE and click on the “Add workspace folder” option. After that, you’ll create the folder with the name you want for your project. And after completing the folder, you will need to open it, and done in “Open folder” and select the folder you just created. Already with the editor open, we will create a python file, the server file. This file we will call by app.py. And we’ll type in the code below:

from flask import Flask from flask_restplus import Api, Resource, fields from werkzeug. contrib.fixers import ProxyFix

This code will import some necessary resources with a direct connection to the flask.

In the next step, we’ll readjust the preview page about the records we’ll create. Then we’ll make the title, description, and API services. For that, we’ll use the code:

app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app, version='1.0', title='Registration',description='...',) ns = api.namespace('register', description='...')

After that, we will start with the types of data that will need for the records. In our case, we will have three types: ID, FIRST, and LAST NAME service, as shown in the code below:

register = api.model('register', { 'id': fields.Integer, 'name': fields.String, 'last name': fields.String})

Here, we’ll have a better idea of attributes. Since we’ll have an ID, FIRST, and LAST NAME service, we can specify them, as the code below shows:

registers = {99:{"id":99,"name":"Anderson","surname":"Henrique"}, 9:{"id":9,"name":"Tatiana","surname":"Moreno"}}

As we can see, the records directly match with the previously created structure.

After we finish the attributes part, we’ll start with the collection, but we’ll first understand a little bit about the GET and POST function. GET is the simplest HTTP request method, the same that browsers use every time you click on a link or access through the address bar. With the instructions, the server transmits the information identified in the URL to the client. The information should never change on the server through a GET request that would be read-only. Still, of course, from the moment the client receives the information, he can do whatever he wants — for example, format the information for presentation in the browser. The POST function should use repetition in the process executed when a POST request gets executed more than once. Besides, POST requests must run the body’s process as a subordinate to the URL that you’re posting. Now, let’s start the collection! For that, we’ll make the registration of an API using the GET service because it will return to the dictionary of previously created records and, besides the “get,” we’ll have to start the marshal. After all, it will bring the list of declared record types and the POST, cause in this way; we’ll give the client the power to add records, remembering that we must associate this service with namespace on the root route. And for that, we’ll start with the code:

@ns.route('/') class CollectionAPI(Resource): @ns.doc('GET=(R)etrieve ALL') @ns.marshal_list_with(register) def get(self): return list(registers.values()) @ns.doc('POST=(C)reate') @ns.expect(register) @ns.marshal_with(register, code=201) def post(self): reg = api.payload registers[reg['id']]=reg return reg, 201

Great! We did our collection!

An essential part is to start what we call an “entity.” An entity is an object of light persistence. Usually, an entity represents a table in a relational database. Each instance of the entity corresponds to a row in that table. It is where we should change the API route, specifying the ID. And besides that, the parameter also needs to be determined. We also have to bring the GET service. However, we won’t list; this time, we’ll use the service as an individual to obtain the registered person’s ID. After that, we will have to bring the PUT, which will update all the system data. In this last step, we will give the DELETE service power because this function will allow the administrator to delete the records created. We will do this by the code:

@ns.route('/<int:id>') @ns.response(404, 'Not found') @ns.param('id', 'ID') class EntityAPI(Resource): @ns.doc('GET=(R)etrieve [one]') @ns.marshal_with(register) def get(self, id): reg= registers[id] if (reg!=None): return reg else: api.abort(404, "Record {} doesn't exist".format(id)) @ns.doc('DEL=(D)elete') @ns.response(204, 201'Deleted') def delete(self, id): del registers[id] return '', 204 @ns.doc('PUT=(U)pdate') @ns.expect(register) @ns.marshal_with(register) def put(self, id): registers[id]=api.payload return api.payload

Well done! We did our entity!

Finally, we will specify the port that we want the server to run, and our application will be ready!

if __name__ == '__main__': app.run(port=8888, debug=True)

Great! We need to go to the VS CODE terminal and type the command: python3 app.py click on the port it opens, and our project will be running correctly!

We can relate REST to the GO; at first, it is essential to mention that REST needs to call any customer; as an example, we will build the first demonstration in GO. And in the next tutorial, we will have the second part of the article, the REST service in full GO.

As we could see before, we have created some services. GET, POST, GET(ID), DELETE, and PUT. The technology we developed in REST, until then, is very transparent. Every part was creating in Flask and Python, and we’ll make the GO client call the GET service. Now, we’ll have to open VSCODE, create a new folder; doing that, we’ll need some libraries, as we can see below:

package main import ( "net/http" "fmt" "io/ioutil" )

After that, we need to specify the link of the code with the URL of our site. If an error occurs, for example, a connection error, it’ll fall into if shown in the code below:

func main() { resp, err := http.Get("http://127.0.0.1:8888/") if err != nil { fmt.Println("An error has occurred!", err) }

If it connects and works, it’ll fall into the code below. So, in this way, we’ll get an answer. He’ll fall into code 200.

if resp.StatusCode == 200 { fmt.Println("The site has been loaded successfully!")

We need to start a display code that shows the response’s body and processing the necessary data in the browser. And in REST, this content is displayed in JSON.

body, err := ioutil.ReadAll(resp.Body) if err != nil { print(err) }else{ fmt.Print(string(body)) }

However, if there is an internal error in the code, any error code will appear, and, for that reason, it will fall into the “else” below.

} else { fmt.Println("The site is broken! Status Code:", resp.StatusCode) } }

Well done! We have finished both the REST API tutorial and the GO language connection. I hope you guys enjoyed it.

Thank you!