Vert.x-Web - Part 2 - REST API's

Trying out some CRUD API's

The following link comes handy: http://vertx.io/blog/some-rest-with-vert-x/
  • GET /api/cars => getAllcars
  • GET /api/cars/:id => get car with id =:id
  • POST /api/car - add a new car
  • PUT /api/car/:id - update a car
Vertex relies on Jackson to handle the JSON format.
Use the JSON.encodePretty to get your JSON response.

This post mainly deals with Get API.

  1. Get static JSON response 
  2. Get data from the MySQL database.

In any API call Ensure to follow these 3 steps- 

  • Create a router - Router helps dispatch request
  • Handler - Handler is the processing units. Process the request. It gets called when the result set is ready.
  • Start the server
  • Ensure the plugin in your pom file has the correct main verticle.

First get API with JSON response.

**Ensure to update your pom file always with the right class name of the verticle.

Step 1: Get a static JSON response:



Step 2: Getting data from the database using JDBI Client.

(http://vertx.io/docs/vertx-jdbc-client/java/)

  1. Add the JDBC Client                       
  2. Creating the client 
    1. Default Shared resouce. Same data source btw multiple client applications.
    2. Creating client without shared data source.
  3. Create the config
  4. Get the connection
  5. Closing the client connection 


Getting Data using the Mysql Client : 

In case you are using the MySQL database you can use the vertex asynchronous client.
(http://vertx.io/blog/using-the-asynchronous-sql-client/)

** You may run into problems while using the mysql client vertx-mysql-postgresql-client 3.4.1 along with vertex-web core v 3.0.0 In such case change the core version to vertex-web 3.2.1

  1. Add the mysql client in the pom.xml file
  2. Configuration is a json object contating the following information 
     { "host" : <your-host>,
      "port" : <your-port>,
      "maxPoolSize" : <maximum-number-of-open-connections>,
      "username" : <your-username>,
      "password" : <your-password>,
      "database" : <name-of-your-database>,
      "charset" : <name-of-the-character-set>,
      "queryTimeout" : <timeout-in-milliseconds>
    }
  3. Create the client using a shared resource 
      mySQLClient = MySQLClient.createShared(vertx, mysqlClientConfig);
  4. Getting the connection 
  5. Close the connection - It is better to close the connection when you are done so that it will be given back to the connection pool and used by some other request.







Comments