Mitchel  Carter

Mitchel Carter

1603504800

HTTP REQUEST Methods-GET, POST, PUT, PATCH, DELETE.

In this article, we are going to learn the most common HTTP methods(POST, GET, PUT, PATCH, DELETE). If you are a beginner then you are confused when using those HTTP methods. Let’s try to clear your confusion through the examples.

We will be using this fake API for a demonstration. with credits to https://jsonplaceholder.typicode.com/

The most commonly used HTTP methods POST, GET, PUT, PATCH, DELETE are similar to CURD (create, update, read, delete) operations in the database. Just try to remember below the key Points

  1. Create NEW record =>POST
  2. read=>GET
  3. If the record exists then update else create a new record=>PUT
  4. update/modify=>PATCH
  5. delete=>DELETE

The Get Method

Get method is used to retrieve or get the information from the given server using a given URL. In REST CURD, it performs the read operation.

_Let’s try GET method _:

Let’s set up an HTML file that you can run locally on your browser. Create a file called get.html.Let’s look at the code :

Image for post

Image for post

Get method Code

Image for post

Image for post

get method output

The Post Method

Post is used for sending data to the server such as uploading a file or transferring some data or adding a new row to the back end table to any kind of web form. In a simple sentence, we can say that the post method is used for inserting new items in the backend server. In REST CRUD operation it performs the create operation.

#get-method #javascript-fetch-api #http-methods #restful-api

What is GEEK

Buddha Community

HTTP REQUEST Methods-GET, POST, PUT, PATCH, DELETE.
Shubham Ankit

Shubham Ankit

1657081614

How to Automate Excel with Python | Python Excel Tutorial (OpenPyXL)

How to Automate Excel with Python

In this article, We will show how we can use python to automate Excel . A useful Python library is Openpyxl which we will learn to do Excel Automation

What is OPENPYXL

Openpyxl is a Python library that is used to read from an Excel file or write to an Excel file. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, adding formulas, and more.

Workbook: A spreadsheet is represented as a workbook in openpyxl. A workbook consists of one or more sheets.

Sheet: A sheet is a single page composed of cells for organizing data.

Cell: The intersection of a row and a column is called a cell. Usually represented by A1, B5, etc.

Row: A row is a horizontal line represented by a number (1,2, etc.).

Column: A column is a vertical line represented by a capital letter (A, B, etc.).

Openpyxl can be installed using the pip command and it is recommended to install it in a virtual environment.

pip install openpyxl

CREATE A NEW WORKBOOK

We start by creating a new spreadsheet, which is called a workbook in Openpyxl. We import the workbook module from Openpyxl and use the function Workbook() which creates a new workbook.

from openpyxl
import Workbook
#creates a new workbook
wb = Workbook()
#Gets the first active worksheet
ws = wb.active
#creating new worksheets by using the create_sheet method

ws1 = wb.create_sheet("sheet1", 0) #inserts at first position
ws2 = wb.create_sheet("sheet2") #inserts at last position
ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position

#Renaming the sheet
ws.title = "Example"

#save the workbook
wb.save(filename = "example.xlsx")

READING DATA FROM WORKBOOK

We load the file using the function load_Workbook() which takes the filename as an argument. The file must be saved in the same working directory.

#loading a workbook
wb = openpyxl.load_workbook("example.xlsx")

 

GETTING SHEETS FROM THE LOADED WORKBOOK

 

#getting sheet names
wb.sheetnames
result = ['sheet1', 'Sheet', 'sheet3', 'sheet2']

#getting a particular sheet
sheet1 = wb["sheet2"]

#getting sheet title
sheet1.title
result = 'sheet2'

#Getting the active sheet
sheetactive = wb.active
result = 'sheet1'

 

ACCESSING CELLS AND CELL VALUES

 

#get a cell from the sheet
sheet1["A1"] <
  Cell 'Sheet1'.A1 >

  #get the cell value
ws["A1"].value 'Segment'

#accessing cell using row and column and assigning a value
d = ws.cell(row = 4, column = 2, value = 10)
d.value
10

 

ITERATING THROUGH ROWS AND COLUMNS

 

#looping through each row and column
for x in range(1, 5):
  for y in range(1, 5):
  print(x, y, ws.cell(row = x, column = y)
    .value)

#getting the highest row number
ws.max_row
701

#getting the highest column number
ws.max_column
19

There are two functions for iterating through rows and columns.

Iter_rows() => returns the rows
Iter_cols() => returns the columns {
  min_row = 4, max_row = 5, min_col = 2, max_col = 5
} => This can be used to set the boundaries
for any iteration.

Example:

#iterating rows
for row in ws.iter_rows(min_row = 2, max_col = 3, max_row = 3):
  for cell in row:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C3 >

  #iterating columns
for col in ws.iter_cols(min_row = 2, max_col = 3, max_row = 3):
  for cell in col:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.C3 >

To get all the rows of the worksheet we use the method worksheet.rows and to get all the columns of the worksheet we use the method worksheet.columns. Similarly, to iterate only through the values we use the method worksheet.values.


Example:

for row in ws.values:
  for value in row:
  print(value)

 

WRITING DATA TO AN EXCEL FILE

Writing to a workbook can be done in many ways such as adding a formula, adding charts, images, updating cell values, inserting rows and columns, etc… We will discuss each of these with an example.

 

CREATING AND SAVING A NEW WORKBOOK

 

#creates a new workbook
wb = openpyxl.Workbook()

#saving the workbook
wb.save("new.xlsx")

 

ADDING AND REMOVING SHEETS

 

#creating a new sheet
ws1 = wb.create_sheet(title = "sheet 2")

#creating a new sheet at index 0
ws2 = wb.create_sheet(index = 0, title = "sheet 0")

#checking the sheet names
wb.sheetnames['sheet 0', 'Sheet', 'sheet 2']

#deleting a sheet
del wb['sheet 0']

#checking sheetnames
wb.sheetnames['Sheet', 'sheet 2']

 

ADDING CELL VALUES

 

#checking the sheet value
ws['B2'].value
null

#adding value to cell
ws['B2'] = 367

#checking value
ws['B2'].value
367

 

ADDING FORMULAS

 

We often require formulas to be included in our Excel datasheet. We can easily add formulas using the Openpyxl module just like you add values to a cell.
 

For example:

import openpyxl
from openpyxl
import Workbook

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']

ws['A9'] = '=SUM(A2:A8)'

wb.save("new2.xlsx")

The above program will add the formula (=SUM(A2:A8)) in cell A9. The result will be as below.

image

 

MERGE/UNMERGE CELLS

Two or more cells can be merged to a rectangular area using the method merge_cells(), and similarly, they can be unmerged using the method unmerge_cells().

For example:
Merge cells

#merge cells B2 to C9
ws.merge_cells('B2:C9')
ws['B2'] = "Merged cells"

Adding the above code to the previous example will merge cells as below.

image

UNMERGE CELLS

 

#unmerge cells B2 to C9
ws.unmerge_cells('B2:C9')

The above code will unmerge cells from B2 to C9.

INSERTING AN IMAGE

To insert an image we import the image function from the module openpyxl.drawing.image. We then load our image and add it to the cell as shown in the below example.

Example:

import openpyxl
from openpyxl
import Workbook
from openpyxl.drawing.image
import Image

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
#loading the image(should be in same folder)
img = Image('logo.png')
ws['A1'] = "Adding image"
#adjusting size
img.height = 130
img.width = 200
#adding img to cell A3

ws.add_image(img, 'A3')

wb.save("new2.xlsx")

Result:

image

CREATING CHARTS

Charts are essential to show a visualization of data. We can create charts from Excel data using the Openpyxl module chart. Different forms of charts such as line charts, bar charts, 3D line charts, etc., can be created. We need to create a reference that contains the data to be used for the chart, which is nothing but a selection of cells (rows and columns). I am using sample data to create a 3D bar chart in the below example:

Example

import openpyxl
from openpyxl
import Workbook
from openpyxl.chart
import BarChart3D, Reference, series

wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active

values = Reference(ws, min_col = 3, min_row = 2, max_col = 3, max_row = 40)
chart = BarChart3D()
chart.add_data(values)
ws.add_chart(chart, "E3")
wb.save("MyChart.xlsx")

Result
image


How to Automate Excel with Python with Video Tutorial

Welcome to another video! In this video, We will cover how we can use python to automate Excel. I'll be going over everything from creating workbooks to accessing individual cells and stylizing cells. There is a ton of things that you can do with Excel but I'll just be covering the core/base things in OpenPyXl.

⭐️ Timestamps ⭐️
00:00 | Introduction
02:14 | Installing openpyxl
03:19 | Testing Installation
04:25 | Loading an Existing Workbook
06:46 | Accessing Worksheets
07:37 | Accessing Cell Values
08:58 | Saving Workbooks
09:52 | Creating, Listing and Changing Sheets
11:50 | Creating a New Workbook
12:39 | Adding/Appending Rows
14:26 | Accessing Multiple Cells
20:46 | Merging Cells
22:27 | Inserting and Deleting Rows
23:35 | Inserting and Deleting Columns
24:48 | Copying and Moving Cells
26:06 | Practical Example, Formulas & Cell Styling

📄 Resources 📄
OpenPyXL Docs: https://openpyxl.readthedocs.io/en/stable/ 
Code Written in This Tutorial: https://github.com/techwithtim/ExcelPythonTutorial 
Subscribe: https://www.youtube.com/c/TechWithTim/featured 

#python 

Mitchel  Carter

Mitchel Carter

1603504800

HTTP REQUEST Methods-GET, POST, PUT, PATCH, DELETE.

In this article, we are going to learn the most common HTTP methods(POST, GET, PUT, PATCH, DELETE). If you are a beginner then you are confused when using those HTTP methods. Let’s try to clear your confusion through the examples.

We will be using this fake API for a demonstration. with credits to https://jsonplaceholder.typicode.com/

The most commonly used HTTP methods POST, GET, PUT, PATCH, DELETE are similar to CURD (create, update, read, delete) operations in the database. Just try to remember below the key Points

  1. Create NEW record =>POST
  2. read=>GET
  3. If the record exists then update else create a new record=>PUT
  4. update/modify=>PATCH
  5. delete=>DELETE

The Get Method

Get method is used to retrieve or get the information from the given server using a given URL. In REST CURD, it performs the read operation.

_Let’s try GET method _:

Let’s set up an HTML file that you can run locally on your browser. Create a file called get.html.Let’s look at the code :

Image for post

Image for post

Get method Code

Image for post

Image for post

get method output

The Post Method

Post is used for sending data to the server such as uploading a file or transferring some data or adding a new row to the back end table to any kind of web form. In a simple sentence, we can say that the post method is used for inserting new items in the backend server. In REST CRUD operation it performs the create operation.

#get-method #javascript-fetch-api #http-methods #restful-api

OAuth2: A Ruby Wrapper for The OAuth 2.0 Protocol.

What

OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. This is a RubyGem for implementing OAuth 2.0 clients and servers in Ruby applications. See the sibling oauth gem for OAuth 1.0 implementations in Ruby.


Release Documentation

Version 2.0.x

2.0.x Readmes

VersionRelease DateReadme
2.0.62022-07-13https://github.com/oauth-xx/oauth2/blob/v2.0.6/README.md
2.0.52022-07-07https://github.com/oauth-xx/oauth2/blob/v2.0.5/README.md
2.0.42022-07-01https://github.com/oauth-xx/oauth2/blob/v2.0.4/README.md
2.0.32022-06-28https://github.com/oauth-xx/oauth2/blob/v2.0.3/README.md
2.0.22022-06-24https://github.com/oauth-xx/oauth2/blob/v2.0.2/README.md
2.0.12022-06-22https://github.com/oauth-xx/oauth2/blob/v2.0.1/README.md
2.0.02022-06-21https://github.com/oauth-xx/oauth2/blob/v2.0.0/README.md

Older Releases

1.4.x Readmes

VersionRelease DateReadme
1.4.10Jul 1, 2022https://github.com/oauth-xx/oauth2/blob/v1.4.10/README.md
1.4.9Feb 20, 2022https://github.com/oauth-xx/oauth2/blob/v1.4.9/README.md
1.4.8Feb 18, 2022https://github.com/oauth-xx/oauth2/blob/v1.4.8/README.md
1.4.7Mar 19, 2021https://github.com/oauth-xx/oauth2/blob/v1.4.7/README.md
1.4.6Mar 19, 2021https://github.com/oauth-xx/oauth2/blob/v1.4.6/README.md
1.4.5Mar 18, 2021https://github.com/oauth-xx/oauth2/blob/v1.4.5/README.md
1.4.4Feb 12, 2020https://github.com/oauth-xx/oauth2/blob/v1.4.4/README.md
1.4.3Jan 29, 2020https://github.com/oauth-xx/oauth2/blob/v1.4.3/README.md
1.4.2Oct 1, 2019https://github.com/oauth-xx/oauth2/blob/v1.4.2/README.md
1.4.1Oct 13, 2018https://github.com/oauth-xx/oauth2/blob/v1.4.1/README.md
1.4.0Jun 9, 2017https://github.com/oauth-xx/oauth2/blob/v1.4.0/README.md

1.3.x Readmes

VersionRelease DateReadme
1.3.1Mar 3, 2017https://github.com/oauth-xx/oauth2/blob/v1.3.1/README.md
1.3.0Dec 27, 2016https://github.com/oauth-xx/oauth2/blob/v1.3.0/README.md

≤= 1.2.x Readmes (2016 and before)

VersionRelease DateReadme
1.2.0Jun 30, 2016https://github.com/oauth-xx/oauth2/blob/v1.2.0/README.md
1.1.0Jan 30, 2016https://github.com/oauth-xx/oauth2/blob/v1.1.0/README.md
1.0.0May 23, 2014https://github.com/oauth-xx/oauth2/blob/v1.0.0/README.md
< 1.0.0Find herehttps://github.com/oauth-xx/oauth2/tags

Status

 Projectbundle add oauth2
1️⃣name, license, docsRubyGems.org License: MIT FOSSA RubyDoc.info InchCI
2️⃣version & activityGem Version Total Downloads Download Rank Source Code Open PRs Closed PRs Next Version
3️⃣maintanence & lintingMaintainability Helpers Depfu Contributors Style Kloc Roll
4️⃣testingOpen Issues Closed Issues Supported Heads Unofficial Support MacOS Windows
5️⃣coverage & securityCodeClimate CodeCov Coveralls Security Policy CodeQL Code Coverage
6️⃣resourcesDiscussion Get help on Codementor Chat Blog Blog
7️⃣spread 💖Liberapay Patrons Sponsor Me Tweet @ Peter 🌏 👼 💻

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add oauth2

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install oauth2

OAuth2 for Enterprise

Available as part of the Tidelift Subscription.

The maintainers of OAuth2 and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

For more see SECURITY.md.

What is new for v2.0?

  • Officially support Ruby versions >= 2.7
  • Unofficially support Ruby versions >= 2.5
  • Incidentally support Ruby versions >= 2.2
  • Drop support for the expired MAC Draft (all versions)
  • Support IETF rfc7523 JWT Bearer Tokens
  • Support IETF rfc7231 Relative Location in Redirect
  • Support IETF rfc6749 Don't set oauth params when nil
  • Support OIDC 1.0 Private Key JWT; based on the OAuth JWT assertion specification (RFC 7523)
  • Support new formats, including from jsonapi.org: application/vdn.api+json, application/vnd.collection+json, application/hal+json, application/problem+json
  • Adds new option to OAuth2::Client#get_token:
    • :access_token_class (AccessToken); user specified class to use for all calls to get_token
  • Adds new option to OAuth2::AccessToken#initialize:
    • :expires_latency (nil); number of seconds by which AccessToken validity will be reduced to offset latency
  • By default, keys are transformed to camel case.
    • Original keys will still work as previously, in most scenarios, thanks to rash_alt gem.
    • However, this is a breaking change if you rely on response.parsed.to_h, as the keys in the result will be camel case.
    • As of version 2.0.4 you can turn key transformation off with the snaky: false option.
  • By default, the :auth_scheme is now :basic_auth (instead of :request_body)
    • Third-party strategies and gems may need to be updated if a provider was requiring client id/secret in the request body
  • ... A lot more

Compatibility

Targeted ruby compatibility is non-EOL versions of Ruby, currently 2.7, 3.0 and 3.1. Compatibility is further distinguished by supported and unsupported versions of Ruby. Ruby is limited to 2.2+ for 2.x releases. See 1-4-stable branch for older rubies.

Ruby Engine Compatibility Policy

This gem is tested against MRI, JRuby, and Truffleruby. Each of those has varying versions that target a specific version of MRI Ruby. This gem should work in the just-listed Ruby engines according to the targeted MRI compatibility in the table below. If you would like to add support for additional engines, first make sure Github Actions supports the engine, then submit a PR to the correct maintenance branch as according to the table below.

Ruby Version Compatibility Policy

If something doesn't work on one of these interpreters, it's a bug.

This library may inadvertently work (or seem to work) on other Ruby implementations, however support will only be provided for the versions listed above.

If you would like this library to support another Ruby version, you may volunteer to be a maintainer. Being a maintainer entails making sure all tests run and pass on that implementation. When something breaks on your implementation, you will be responsible for providing patches in a timely fashion. If critical issues for a particular implementation exist at the time of a major release, support for that Ruby version may be dropped.

 Ruby OAuth2 VersionMaintenance BranchSupported OfficiallySupported UnofficiallySupported Incidentally
1️⃣2.0.xmaster2.7, 3.0, 3.12.5, 2.62.2, 2.3, 2.4
2️⃣1.4.x1-4-stable2.5, 2.6, 2.7, 3.0, 3.12.1, 2.2, 2.3, 2.41.9, 2.0
3️⃣olderN/ABest of luck to you!Please upgrade! 

NOTE: The 1.4 series will only receive critical security updates. See SECURITY.md

Usage Examples

authorize_url and token_url are on site root (Just Works!)

require 'oauth2'
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.org')
# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
client.auth_code.authorize_url(redirect_uri: 'http://localhost:8080/oauth2/callback')
# => "https://example.org/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"

access = client.auth_code.get_token('authorization_code_value', redirect_uri: 'http://localhost:8080/oauth2/callback', headers: {'Authorization' => 'Basic some_password'})
response = access.get('/api/resource', params: {'query_foo' => 'bar'})
response.class.name
# => OAuth2::Response

Relative authorize_url and token_url (Not on site root, Just Works!)

In above example, the default Authorization URL is oauth/authorize and default Access Token URL is oauth/token, and, as they are missing a leading /, both are relative.

client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.org/nested/directory/on/your/server')
# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
client.auth_code.authorize_url(redirect_uri: 'http://localhost:8080/oauth2/callback')
# => "https://example.org/nested/directory/on/your/server/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"

Customize authorize_url and token_url

You can specify custom URLs for authorization and access token, and when using a leading / they will not be relative, as shown below:

client = OAuth2::Client.new('client_id', 'client_secret',
                            site: 'https://example.org/nested/directory/on/your/server',
                            authorize_url: '/jaunty/authorize/',
                            token_url: '/stirrups/access_token')
# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
client.auth_code.authorize_url(redirect_uri: 'http://localhost:8080/oauth2/callback')
# => "https://example.org/jaunty/authorize/?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
client.class.name
# => OAuth2::Client

snake_case and indifferent access in Response#parsed

response = access.get('/api/resource', params: {'query_foo' => 'bar'})
# Even if the actual response is CamelCase. it will be made available as snaky:
JSON.parse(response.body)         # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
response.parsed                   # => {"access_token"=>"aaaaaaaa", "additional_data"=>"additional"}
response.parsed.access_token      # => "aaaaaaaa"
response.parsed[:access_token]    # => "aaaaaaaa"
response.parsed.additional_data   # => "additional"
response.parsed[:additional_data] # => "additional"
response.parsed.class.name        # => OAuth2::SnakyHash (subclass of Hashie::Mash::Rash, from `rash_alt` gem)

What if I hate snakes and/or indifference?

response = access.get('/api/resource', params: {'query_foo' => 'bar'}, snaky: false)
JSON.parse(response.body)         # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
response.parsed                   # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
response.parsed['accessToken']    # => "aaaaaaaa"
response.parsed['additionalData'] # => "additional"
response.parsed.class.name        # => Hash (just, regular old Hash)

Debugging

Set an environment variable, however you would normally do that.

# will log both request and response, including bodies
ENV['OAUTH_DEBUG'] = 'true'

By default, debug output will go to $stdout. This can be overridden when initializing your OAuth2::Client.

require 'oauth2'
client = OAuth2::Client.new(
  'client_id',
  'client_secret',
  site: 'https://example.org',
  logger: Logger.new('example.log', 'weekly')
)

OAuth2::Response

The AccessToken methods #get, #post, #put and #delete and the generic #request will return an instance of the #OAuth2::Response class.

This instance contains a #parsed method that will parse the response body and return a Hash-like OAuth2::SnakyHash if the Content-Type is application/x-www-form-urlencoded or if the body is a JSON object. It will return an Array if the body is a JSON array. Otherwise, it will return the original body string.

The original response body, headers, and status can be accessed via their respective methods.

OAuth2::AccessToken

If you have an existing Access Token for a user, you can initialize an instance using various class methods including the standard new, from_hash (if you have a hash of the values), or from_kvform (if you have an application/x-www-form-urlencoded encoded string of the values).

OAuth2::Error

On 400+ status code responses, an OAuth2::Error will be raised. If it is a standard OAuth2 error response, the body will be parsed and #code and #description will contain the values provided from the error and error_description parameters. The #response property of OAuth2::Error will always contain the OAuth2::Response instance.

If you do not want an error to be raised, you may use :raise_errors => false option on initialization of the client. In this case the OAuth2::Response instance will be returned as usual and on 400+ status code responses, the Response instance will contain the OAuth2::Error instance.

Authorization Grants

Currently the Authorization Code, Implicit, Resource Owner Password Credentials, Client Credentials, and Assertion authentication grant types have helper strategy classes that simplify client use. They are available via the #auth_code, #implicit, #password, #client_credentials, and #assertion methods respectively.

These aren't full examples, but demonstrative of the differences between usage for each strategy.

auth_url = client.auth_code.authorize_url(redirect_uri: 'http://localhost:8080/oauth/callback')
access = client.auth_code.get_token('code_value', redirect_uri: 'http://localhost:8080/oauth/callback')

auth_url = client.implicit.authorize_url(redirect_uri: 'http://localhost:8080/oauth/callback')
# get the token params in the callback and
access = OAuth2::AccessToken.from_kvform(client, query_string)

access = client.password.get_token('username', 'password')

access = client.client_credentials.get_token

# Client Assertion Strategy
# see: https://tools.ietf.org/html/rfc7523
claimset = {
  iss: 'http://localhost:3001',
  aud: 'http://localhost:8080/oauth2/token',
  sub: 'me@example.com',
  exp: Time.now.utc.to_i + 3600,
}
assertion_params = [claimset, 'HS256', 'secret_key']
access = client.assertion.get_token(assertion_params)

# The `access` (i.e. access token) is then used like so:
access.token # actual access_token string, if you need it somewhere
access.get('/api/stuff') # making api calls with access token

If you want to specify additional headers to be sent out with the request, add a 'headers' hash under 'params':

access = client.auth_code.get_token('code_value', redirect_uri: 'http://localhost:8080/oauth/callback', headers: {'Some' => 'Header'})

You can always use the #request method on the OAuth2::Client instance to make requests for tokens for any Authentication grant type.

Versioning

This library aims to adhere to Semantic Versioning 2.0.0. Violations of this scheme should be reported as bugs. Specifically, if a minor or patch version is released that breaks backward compatibility, a new version should be immediately released that restores compatibility. Breaking changes to the public API will only be introduced with new major versions.

As a result of this policy, you can (and should) specify a dependency on this gem using the Pessimistic Version Constraint with two digits of precision.

For example:

spec.add_dependency 'oauth2', '~> 2.0'

License

License: MIT

FOSSA Status

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

See CONTRIBUTING.md

Contributors

Contributors

Made with contributors-img.

Code of Conduct

Everyone interacting in the OAuth2 project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.


Author: oauth-xx
Source code: https://github.com/oauth-xx/oauth2
License: MIT license

#ruby #ruby-on-rails 

Justice  Reilly

Justice Reilly

1593257100

Node.js Crash Course Tutorial #10 - Get, Post & Delete Requests

In this node.js tutorial we’ll set up some route handlers for different request types. We’ll also look at how to handle post requests and delete requests.

#node.js #node #delete requests #get #post

6 Things About HTTP Request in Dart For Beginners

Introduction

If you are here and a beginner, that means you want to learn everything about making an API request using Dart in Flutter, then you are in the right place for the HTTP tutorial. So without wasting any time, let’s start with this flutter tutorial. We will cover the essential topics required to work with the HTTP request in Dart.

What is Rest API in Dart ?

rest api flow

Rest APIs are a way to fetch data from the internet in flutter or communicate the server from the app and get some essential information from your server to the app. This information can be regarding your app’s data, user’s data, or any data you want to share globally from your app to all of your users.

This HTTP request fetches in a unique JSON format, and then the information is fetched from the JSON and put in the UI of the app.

Every programming language has a way of some internet connectivity i.e, use this rest API developed on the server and fetch data from the internet. To use this request feature, we have to add HTTP package in flutter, add this flutter package add in your project to use the http feature. Add this HTTP package to your pubspec.yaml, and run a command in terminal :

flutter packages get

#dart #flutter #async await #async function #cancel http api request in flutter #fetch data from the internet #flutter cancel future #flutter get request example #flutter post request example #future of flutter #http tutorial