Arquivo da tag: Rest

Jira – Basic auth for REST APIs

https://developer.atlassian.com/cloud/jira/platform/jira-rest-api-basic-authentication/
https://confluence.atlassian.com/cloud/api-tokens-938839638.html
https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#api-api-3-issue-issueIdOrKey-worklog-get
curl -v https://mysite.atlassian.net --user me@example.com:my-api-token

HTTP Posts in Ruby

Sometimes I need to make simple HTTP posts in a Ruby script. Using a 3rd party library may be too clunky for such a simple script.

This post helps a lot, but it doesn’t cover all my needs. Specifically, when working with the Switchvox API, the API methods are expected to be a JSON parameter.

Let’s start by imply posting some JSON.

Post some JSON

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse("http://localhost:3000/users")

header = {'Content-Type': 'text/json'}
user = {user: {
                   name: 'Bob',
                   email: 'bob@example.com'
                      }
            }

# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json

# Send the request
response = http.request(request)

This will simply submit a POST request with the JSON as the body.

But, there were some methods that required a file be submitted with the JSON? Things get a little more complicated when you do this, but it is still manageable.

Post a file with some JSON

require 'net/http'
require 'uri'
require 'json'
require 'mime/types'

uri = URI.parse("http://localhost:3000/users")
BOUNDARY = "AaB03x"

header = {"Content-Type": "multipart/form-data, boundary=#{BOUNDARY}"}
user = {user: {
                   name: 'Bob',
                   email: 'bob@example.com'
                      }
            }
file = "test_file.xml"

# We're going to compile all the parts of the body into an array, then join them into one single string
# This method reads the given file into memory all at once, thus it might not work well for large files
post_body = []

# Add the file Data
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"user[][image]\"; filename=\"#{File.bsename(file)}\"\r\n"
post_body << "Content-Type: #{MIME::Types.type_for(file)}\r\n\r\n"
post_body << File.read(file)

# Add the JSON
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"user[]\"\r\n\r\n"
post_body << user.to_json
post_body << "\r\n\r\n--#{BOUNDARY}--\r\n"

# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = post_body.join

# Send the request
response = http.request(request)

And there you have it! A multipart HTTP Post in Ruby without an external library. You can probably see how you could add multiple files and sets JSON objects.

Is it worth not using a 3rd party library and doing it yourself?

https://coderwall.com/p/c-mu-a/http-posts-in-ruby

Spring REST – Download de .pdf

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);
 
    // generate the file
    PdfUtil.showHelp(emp);
 
    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);
 
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
    return response;
}

Salvando imagens Base64 via Web Service REST – Java/Jersey

...
import java.io.ByteArrayInputStrem;
import Javax.ws.rs.FormParam;
import org.apache.commons.io.IOUtils;
...
public class CarResource {
  ...
  @Post
  @Path("/postPhotoBase64")
  @Cunsumes(MediaType.APPLICATION_FORM_URLENCODED)
  public Response postPhotoBase64(@FormParam("fileName") String fileName, @FormParam("base64") String base64) {
    ...
    byte[] bytes = Base64.getDecoder().decode(base64);
    InputStream in = new ByteArrayInputStream(bytes);
    File tmpDir = new File(System.getProperty("java.io.tmpdir"), "cars");
    if (!tmpDir.exists()) {
      tmpDir.mkdir();
    }
    File file = new File(tmpDir, "Nome_Arquivo");
    FileOutputStream out = new FileOutputStream(file);
    IOUtils.copy(in, out);
    IOUtils.closeQuietly(out);
  }
}