question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I'm trying to do a simple insert into a postgres table, but am getting an error that the value I'm trying to insert is being interpreted as a column name INSERT INTO "imageTagBusinessMainCategory" (id, businessMainCategory) VALUES (DEFAULT, "auto dealer") Where id is set up to be the primary key, and auto increment, a...
Use 'auto dealer' instead. PostgreSQL interprets " as being quotes for identifiers, ' as being quotes for strings. Also: If this is a new project, just don't use mixed case tables; it is a source of frustration later. Instead of being able to use any case in your SQL statements, you must both quote the identifier name...
PostgreSQL
12,428,496
138
I am trying to write the following query on postgresql: select name, author_id, count(1), (select count(1) from names as n2 where n2.id = n1.id and t2.author_id = t1.author_id ) from names as n1 group by name, author_id This would certainly work on Microsoft SQL Server but it do...
I'm not sure I understand your intent perfectly, but perhaps the following would be close to what you want: select n1.name, n1.author_id, count_1, total_count from (select id, name, author_id, count(1) as count_1 from names group by id, name, author_id) n1 inner join (select id, author_id, count(1...
PostgreSQL
3,004,887
137
I want to remotely connect to a Postgres instance. I know we can do this using the psql command passing the hostname I tried the following: psql -U postgres -p 5432 -h hostname I modified the /etc/postgresql/9.3/main/pg_hba.conf file on the target machine to allow remote connections by default I added the following li...
I resolved this issue using below options: Whitelist your DB host from your network team to make sure you have access to remote host Install postgreSQL version 4 or above Run below command: psql -h <REMOTE HOST> -p <REMOTE PORT> -U <DB_USER> <DB_NAME>
PostgreSQL
32,824,388
136
I have a table where column is of datatype timestamp Which contains records multiple records for a day I want to select all rows corresponding to day How do I do it?
Assuming you actually mean timestamp because there is no datetime in Postgres Cast the timestamp column to a date, that will remove the time part: select * from the_table where the_timestamp_column::date = date '2015-07-15'; This will return all rows from July, 15th. Note that the above will not use an index on the_t...
PostgreSQL
31,433,747
136
Is something like this possible? INSERT INTO Table2 (val) VALUES ((INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id)); like using the return value as value to insert a row in a second table with a reference to the first table?
You can do so starting with Postgres 9.1: with rows as ( INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id ) INSERT INTO Table2 (val) SELECT id FROM rows In the meanwhile, if you're only interested in the id, you can do so with a trigger: create function t1_ins_into_t2() returns trigger as $$ begin insert ...
PostgreSQL
6,560,447
136
The table in question contains roughly ten million rows. for event in Event.objects.all(): print event This causes memory usage to increase steadily to 4 GB or so, at which point the rows print rapidly. The lengthy delay before the first row printed surprised me – I expected it to print almost instantly. I also tr...
Nate C was close, but not quite. From the docs: You can evaluate a QuerySet in the following ways: Iteration. A QuerySet is iterable, and it executes its database query the first time you iterate over it. For example, this will print the headline of all entries in the database: for e in Entry.objects.all(): print...
PostgreSQL
4,222,176
136
I am working on a web application using Python (Django) and would like to know whether MySQL or PostgreSQL would be more suitable when deploying for production. In one podcast Joel said that he had some problems with MySQL and the data wasn't consistent. I would like to know whether someone had any such problems. Also ...
A note to future readers: The text below was last edited in August 2008. That's nearly 11 years ago as of this edit. Software can change rapidly from version to version, so before you go choosing a DBMS based on the advice below, do some research to see if it's still accurate. Check for newer answers below. Better? My...
PostgreSQL
27,435
136
How can I do such query in Postgres? IF (select count(*) from orders) > 0 THEN DELETE from orders ELSE INSERT INTO orders values (1,2,3);
DO $do$ BEGIN IF EXISTS (SELECT FROM orders) THEN DELETE FROM orders; ELSE INSERT INTO orders VALUES (1,2,3); END IF; END $do$ There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc ...
PostgreSQL
11,299,037
135
I'm using Heroku with the Crane Postgres option and I was running a query on the database from my local machine when my local machine crashed. If I run select * from pg_stat_activity one of the entries has <IDLE> in transaction in the current_query_text column. As a result, I can't drop the table that was being writ...
This is a general PostgreSQL answer, and not specific to Heroku Possibly easiest quickfix The simple-stupid answer to this question may be ... just restart postgresql! Here is another way of quickly killing all long-lasting "idle in transaction": SELECT pg_terminate_backend(pid) from pg_stat_activity WHERE state in ('...
PostgreSQL
11,291,456
135
The statement gives me the date and time. How could I modify the statement so that it returns only the date (and not the time)? SELECT to_timestamp( TRUNC( CAST( epoch_ms AS bigint ) / 1000 ) );
You use to_timestamp function and then cast the timestamp to date select to_timestamp(epoch_column)::date; You can use more standard cast instead of :: select cast(to_timestamp(epoch_column) as date); More details: /* Current time */ select now(); -- returns timestamp /* Epoch from current time; Epoch is numbe...
PostgreSQL
16,609,722
134
I need to run a select without actually connecting to any table. I just have a predefined hardcoded set of values I need to loop over: foo bar fooBar And I want to loop through those values. I can do: select 'foo', 'bar', 'fooBar'; But this returns it as one row: ?column? | ?column? | ?column? ----------+----------...
select a from ( values ('foo'), ('bar'), ('fooBar') ) s(a); http://www.postgresql.org/docs/current/static/queries-values.html
PostgreSQL
15,948,614
134
How can I query all GRANTS granted to an object in postgres? For example I have table "mytable": GRANT SELECT, INSERT ON mytable TO user1 GRANT UPDATE ON mytable TO user2 I need somthing which gives me: user1: SELECT, INSERT user2: UPDATE
I already found it: SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_name='mytable'
PostgreSQL
7,336,413
134
How to use newline character in PostgreSQL? This is an incorrect script from my experiment: select 'test line 1'||'\n'||'test line 2'; I want the sql editor display this result from my script above: test line 1 test line 2 But unfortunately I just get this result from my script when I run it in sql editor: test line ...
The backslash has no special meaning in SQL, so '\n' is a backslash followed by the character n To use "escape sequences" in a string literal you need to use an "extended" constant: select 'test line 1'||E'\n'||'test line 2'; Another option is to use the chr() function: select 'test line 1'||chr(10)||'test line 2'; O...
PostgreSQL
36,028,908
133
I'm trying to integrate PostgreSQL and SQLAlchemy but SQLAlchemy.create_all() is not creating any tables from my models. My code: from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'...
You should put your model class before create_all() call, like this: from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.In...
PostgreSQL
20,744,277
133
I was trying to delete PostgreSQL user: DROP USER ryan; I received this error: Error in query: ERROR: role "ryan" cannot be dropped because some objects depend on it DETAIL: privileges for database mydatabase I looked for a solution from these threads: PostgreSQL - how to quickly drop a user with existing privileg...
DROP USER (or DROP ROLE, same thing) cannot proceed while the role still owns anything or has any granted privileges on other objects. Get rid of all privileges with DROP OWNED (which isn't too obvious from the wording). The manual: [...] Any privileges granted to the given roles on objects in the current database and...
PostgreSQL
51,256,454
132
I installed Postgres with this command sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev Using psql --version on terminal I get psql (PostgreSQL) 9.3.4 then I installed pgadmin with sudo apt-get install pgadmin3 Later I opened the UI and create the server with this information but this e...
Modify password for role postgres: sudo -u postgres psql postgres alter user postgres with password 'postgres'; Now connect to pgadmin using username postgres and password postgres Now you can create roles & databases using pgAdmin How to change PostgreSQL user password?
PostgreSQL
24,917,832
132
What is the best way to find records with duplicate values across multiple columns using Postgres, and Activerecord? I found this solution here: User.find(:all, :group => [:first, :email], :having => "count(*) > 1" ) But it doesn't seem to work with postgres. I'm getting this error: PG::GroupingError: ERROR: column "p...
Tested & Working Version User.select(:first,:email).group(:first,:email).having("count(*) > 1") Also, this is a little unrelated but handy. If you want to see how times each combination was found, put .size at the end: User.select(:first,:email).group(:first,:email).having("count(*) > 1").size and you'll get a result...
PostgreSQL
21,669,202
132
In Ubuntu, I installed PostgreSQL database and created a superuser for the server. If I forgot the password of the postgresql superuser, how can I reset it (the password) for that user? I tried uninstalling it and then installing it again but the previously created superuser is retained.
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user. Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule: # Database administrative login by ...
PostgreSQL
14,588,212
132
I need to sort a PostgreSQL table ascending by a date/time field, e.g. last_updated. But that field is allowed to be empty or null and I want records with null in last_updated come before non-null last_updated. Is this possible? order by last_updated asc -- and null last_updated records first ??
Postgres has the NULLS FIRST | LAST modifiers for ORDER BY expression: ... ORDER BY last_updated NULLS FIRST The typical use case is with descending sort order (DESC), which produces the complete inversion of the default ascending order (ASC) with null values first - which is often not desirable. To sort NULL values l...
PostgreSQL
9,510,509
132
Is there a postgresql function that will return a timestamp rounded to the nearest minute? The input value is a timestamp and the return value should be a timestamp.
Use the built-in function date_trunc(text, timestamp), for example: select date_trunc('minute', now()) Edit: This truncates to the most recent minute. To get a rounded result, add 30 seconds to the timestamp first, for example: select date_trunc('minute', now() + interval '30 second') This returns the nearest minute....
PostgreSQL
6,195,439
132
I would like to define a best practice for storing timestamps in my Postgres database in the context of a multi-timezone project. I can choose TIMESTAMP WITHOUT TIME ZONE and remember which timezone was used at insertion time for this field choose TIMESTAMP WITHOUT TIME ZONE and add another field which will contain t...
First off, PostgreSQL’s time handling and arithmetic is fantastic and Option 3 is fine in the general case. It is, however, an incomplete view of time and timezones and can be supplemented: Store the name of a user’s time zone as a user preference (e.g. America/Los_Angeles, not -0700). Have user events/time data subm...
PostgreSQL
6,151,084
132
When creating a table in PostgreSQL, default constraint names will assigned if not provided: CREATE TABLE example ( a integer, b integer, UNIQUE (a, b) ); But using ALTER TABLE to add a constraint it seems a name is mandatory: ALTER TABLE example ADD CONSTRAINT my_explicit_constraint_name UNIQUE (a, b); T...
The standard names for indexes in PostgreSQL are: {tablename}_{columnname(s)}_{suffix} where the suffix is one of the following: pkey for a Primary Key constraint key for a Unique constraint excl for an Exclusion constraint idx for any other kind of index fkey for a Foreign key check for a Check constraint Standard...
PostgreSQL
4,107,915
132
OperationalError at /admin/ FATAL: Peer authentication failed for user "myuser" This is the error I am receiving when I try to get to my Django admin site. I had been using MySQL database no problem. I am new to PostgreSQL, but decided to switch because the host I ultimately plan to use for this project does not hav...
I took a peek at the exception, noticed it had to do with my connection settings. Went back to settings.py, and saw I did not have a Host setup. Add localhost and voila. My settings.py did not have a HOST for MySQL database, but I needed to add one for PostgreSQL to work. In my case, I added localhost to the HOST setti...
PostgreSQL
8,167,602
131
Postgres is the database Can I use a NULL value for a IN clause? example: SELECT * FROM tbl_name WHERE id_field IN ('value1', 'value2', 'value3', NULL) I want to limit to these four values. I have tried the above statement and it doesn't work, well it executes but doesn't add the records with NULL id_fields. I have al...
An in statement will be parsed identically to field=val1 or field=val2 or field=val3. Putting a null in there will boil down to field=null which won't work. (Comment by Marc B) I would do this for clairity SELECT * FROM tbl_name WHERE (id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)
PostgreSQL
6,362,112
130
I'm in the process of creating a table and it made me wonder. If I store, say cars that has a make (fx BMW, Audi ect.), will it make any difference on the query speed if I store the make as an int or varchar. So is SELECT * FROM table WHERE make = 5 AND ...; Faster/slower than SELECT * FROM table WHERE make = 'audi' A...
Int comparisons are faster than varchar comparisons, for the simple fact that ints take up much less space than varchars. This holds true both for unindexed and indexed access. The fastest way to go is an indexed int column. As I see you've tagged the question postgreql, you might be interested in the space usage of d...
PostgreSQL
2,346,920
130
I get the following error when inserting data from mysql into postgres. Do I have to manually remove all null characters from my input data? Is there a way to get postgres to do this for me? ERROR: invalid byte sequence for encoding "UTF8": 0x00
PostgreSQL doesn't support storing NULL (\0x00) characters in text fields (this is obviously different from the database NULL value, which is fully supported). Source: http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-UESCAPE If you need to store the NULL character, you must use a byt...
PostgreSQL
1,347,646
130
We have Spring-boot/Hibernate/PostgreSQL application in our project and use Hikari as the connection pool. We keep running into the following problem: after few hours active connections number grows to the limit and we get the errors like this (full stack trace is at the end of the question): Caused by: java.sql.SQLTra...
I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting th...
PostgreSQL
32,968,530
129
I am trying to connect postgresql but I am getting this error. org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. My pg_hba.conf file is like this. TYPE DATABASE USER CIDR-ADDRESS ME...
The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection. Do what the error message says: Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections You haven't shown the command that produces the error. Assuming...
PostgreSQL
20,825,734
129
Since my approach for a test query which I worked on in this question did not work out, I'm trying something else now. Is there a way to tell pg's random() function to get me only numbers between 1 and 10?
If by numbers between 1 and 10 you mean any float that is >= 1 and < 10, then it's easy: select random() * 9 + 1 This can be easily tested with: # select min(i), max(i) from ( select random() * 9 + 1 as i from generate_series(1,1000000) ) q; min | max -----------------+------------------ 1.0000...
PostgreSQL
1,400,505
129
Is it possible to combine multiple CTEs in single query? I am looking for way to get result like this: WITH cte1 AS ( ... ), WITH RECURSIVE cte2 AS ( ... ), WITH cte3 AS ( ... ) SELECT ... FROM cte3 WHERE ... As you can see, I have one recursive CTE and two non recursive.
Use the key word WITH once at the top. If any of your Common Table Expressions (CTE) are recursive (rCTE) you have to add the keyword RECURSIVE at the top once also, even if not all CTEs are recursive: WITH RECURSIVE cte1 AS (...) -- can still be non-recursive , cte2 AS (SELECT ... UNION ALL ...
PostgreSQL
35,248,217
128
For Postgres, I keep getting this error multiple times even though I have already set the location of the bin folder to the path variable in Windows 8. Is there something else I'm missing?
This answer has been added to the documentation, but in case you are still looking. An update because I was trying it on Windows 10 you do need to set the path to the following: ;C:\Program Files\PostgreSQL\14\bin ;C:\Program Files\PostgreSQL\9.5\lib PS : 14 is the current version, check whatever version you are on. Yo...
PostgreSQL
30,401,460
128
Postgres 9.1 database contains tables yksus1 .. ykssu9 in public schema. pgAdmin shows those definitions as in code below. How to move those tables to firma1 schema ? Other tables in firma1 schema have foreign key references to those table primay keys. Foreign key references to those tables are only from tables in fir...
ALTER TABLE yksus1 SET SCHEMA firma1; More details in the manual: http://www.postgresql.org/docs/current/static/sql-altertable.html Associated indexes, constraints, and sequences owned by table columns are moved as well. Not sure about the trigger function though, but there is an equivalent ALTER FUNCTION .. SE...
PostgreSQL
17,770,117
128
1 S postgres 5038 876 0 80 0 - 11962 sk_wai 09:57 ? 00:00:00 postgres: postgres my_app ::1(45035) idle 1 S postgres 9796 876 0 80 0 - 11964 sk_wai 11:01 ? 00:00:00 postgres: postgres my_app ::1(43084) idle ...
It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction sessions, but with too many connections overall. Killing connections is not the right answer for that, but it's an OK-ish temporary workaround. Rather than...
PostgreSQL
13,236,160
128
I'm receiving this message but I can't find the postgresql.conf file: OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is ...
On my machine: C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
PostgreSQL
4,465,475
128
I have just installed Postgres and have been tinkering with it and various configurations for 1-2 hours. I am stuck on being unable to change to the postgres-user $ su - postgres yields the following error: su: unknown login: postgres $ sudo -u postgres psql yields the following error: sudo: unknown user: postgres Thes...
psql: Logs me in with my default username psql -U postgres: Logs me in as the postgres user Sudo doesn't seem to be required for me. I use Postgres.app for my OS X postgres database. It removed the headache of making sure the installation was working and the database server was launched properly. Check it out here: htt...
PostgreSQL
21,122,598
127
I have a rails app that's databases are in SQLite (The dev and production). Since I am moving to heroku, I want to convert my database to PostgreSQL. Anyways, I heard that the local, development, database does not need to be changed from SQLite, so I don't need to change that, however, how do I go about changing the pr...
You can change your database.yml to this instead of using the out of the box sqlite one: development: adapter: postgresql encoding: utf8 database: project_development pool: 5 username: password: test: &TEST adapter: postgresql encoding: utf8 database: project_test pool: 5 username: password: ...
PostgreSQL
6,710,654
127
I've managed to bork my local development environment. All my local Rails apps are now giving the error: PGError could not connect to server: Permission denied Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"? I've no idea what's caused this. Whil...
This really looks like a file permissions error. Unix domain sockets are files and have user permissions just like any other. It looks as though the OSX user attempting to access the database does not have file permissions to access the socket file. To confirm this I've done some tests on Ubuntu and psql to try to g...
PostgreSQL
8,465,508
126
I have a defined an array field in postgresql 9.4 database: character varying(64)[] Can I have an empty array e.g. {} for default value of that field? What will be the syntax for setting so? I'm getting following error in case of setting just brackets {}: SQL error: ERROR: syntax error at or near "{" LINE 1: ...pub...
You need to use the explicit array initializer and cast that to the correct type: ALTER TABLE public.accounts ALTER COLUMN pwd_history SET DEFAULT array[]::varchar[];
PostgreSQL
30,933,266
125
I have tried using host variable PGPASSWORD and .pgpass and neither of these two will allow me to authenticate to the database. I have chmod'd .pgpass to appropriate permissions and also tried: export PGPASSWORD=mypass and PGPASSWORD=mypass The password DOES contain a \ however I was encasing it in single quotes PGPAS...
The Quick Solution The problem is that it's trying to perform local peer authentication based on your current username. If you would like to use a password you must specify the hostname with -h. pg_dump dbname -U username -h localhost -F c Explanation This is due to the following in your pg_hba.conf local all ...
PostgreSQL
10,430,645
125
I have PostgreSQL 9.2 Installed in Windows 7 and I have windows XP installed in Virtual Machine, how do I connect these two databases and allow remote access to add/edit the database from both Systems ?
In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files: postgresql.conf pg_hba.conf Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the para...
PostgreSQL
18,580,066
124
I have column arr which is of type array. I need to get rows, where arr column contains value s This query: SELECT * FROM table WHERE arr @> ARRAY['s'] gives the error: ERROR: operator does not exist: character varying[] @> text[] Why does it not work? p.s. I know about any() operator, but why doesn't @> work?
Try SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]
PostgreSQL
16,606,357
124
database.yml: # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' development: adapter: postgresql encoding: utf8 database: sampleapp_dev #can be anything unique #host: localhost #username: 7stud #password: #adapter: sqlite3 #databas...
After making changes to the pg_hba.conf or postgresql.conf files, the cluster needs to be reloaded to pick up the changes. From the command line: pg_ctl reload From within a db (as superuser): select pg_reload_conf(); From PGAdmin: right-click db name, select "Reload Configuration" Note: the reload is not sufficient fo...
PostgreSQL
17,996,957
123
I have the following simplified table in Postgres: User Model id (UUID) uid (varchar) name (varchar) I would like a query that can find the user on either its UUID id or its text uid. SELECT * FROM user WHERE id = 'jsdfhiureeirh' or uid = 'jsdfhiureeirh'; My query generates an invalid input syntax for uuid since I...
Found it! Casting the UUID column to ::text stops the error. Not sure about the performance hit but on about 5000 rows I get more than adequate performance. SELECT * FROM user WHERE id::text = 'jsdfhiureeirh' OR uid = 'jsdfhiureeirh'; SELECT * FROM user WHERE id::text = '33bb9554-c616-42e6-a9c6-88d3bba4221c' OR uid...
PostgreSQL
46,433,459
122
I have the following table called module_data. Currently it has three rows of entries: id data 0ab5203b-9157-4934-8aba-1512afb0abd0 {"title":"Board of Supervisors Meeting","id":"1i3Ytw1mw98"} 7ee33a18-63da-4432-8967-bde5a44347a0 {"title":"Board of Supervisors Meeting","id"...
If the data column is text type, then use ->> on cast: select * from module_data where data::json->>'title' like '%Board%' If it's already json: select * from module_data where data->>'title' like '%Board%'
PostgreSQL
42,918,348
122
I have a PostgreSQL database on a Linux system that I want to access from my Windows PC. But the only Windows binaries I have been able to find are the full installer, which includes the database server and client. Is it possible to get a client-only Windows binary install for PostgreSQL from anywhere? (To clarify, I w...
As of 2020, when you click download the full installer from here , click next and next and you get the option to install only the command line - tools . Remember to add the path to the bin folder in the PATH variable.
PostgreSQL
33,854,798
122
I've been instructed "not to bother with LIKE" and use ~ instead. What is wrong with LIKE and how is ~ different? Does ~ have a name in this context or do people say "use the tilde operator"?
~ is the regular expression operator, and has the capabilities implied by that. You can specify a full range of regular expression wildcards and quantifiers; see the documentation for details. It is certainly more powerful than LIKE, and should be used when that power is needed, but they serve different purposes.
PostgreSQL
12,452,395
122
I have a table of about 100M rows that I am going to copy to alter, adding an index. I'm not so concerned with the time it takes to create the new table, but will the created index be more efficient if I alter the table before inserting any data or insert the data first and then add the index?
Creating index after data insert is more efficient way (it even often recomended to drop index before batch import and after import recreate it). Syntetic example (PostgreSQL 9.1, slow development machine, one million rows): CREATE TABLE test1(id serial, x integer); INSERT INTO test1(id, x) SELECT x.id, x.id*100 FROM ...
PostgreSQL
3,688,731
122
Is there a tool or method to analyze Postgres, and determine what missing indexes should be created, and which unused indexes should be removed? I have a little experience doing this with the "profiler" tool for SQLServer, but I'm not aware of a similar tool included with Postgres.
I like this to find missing indexes: SELECT relname AS TableName, to_char(seq_scan, '999,999,999,999') AS TotalSeqScan, to_char(idx_scan, '999,999,999,999') AS TotalIndexScan, to_char(n_live_tup, '999,999,999,999') AS...
PostgreSQL
3,318,727
122
I'm trying to build a Flask app using Postgres with Docker. I'd like to connect to an AWS RDS instance of Postgres, but use Docker for my Flask app. However, when trying to set up psycopg2 it runs into an error because it can't find pg_config. Here's the error: Building api Step 1/5 : FROM python:3.6.3-alpine3.6 ---> ...
Tested with Python 3.4.8, 3.5.5, 3.6.5 and 2.7.14 (just replace 3 with 2): # You can use a specific version too, like python:3.6.5-alpine3.7 FROM python:3-alpine WORKDIR /usr/src/app COPY requirements.txt . RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgres...
PostgreSQL
46,711,990
121
I'm trying to map the results of a query to JSON using the row_to_json() function that was added in PostgreSQL 9.2. I'm having trouble figuring out the best way to represent joined rows as nested objects (1:1 relations) Here's what I've tried (setup code: tables, sample data, followed by query): -- some test tables to ...
Update: In PostgreSQL 9.4 this improves a lot with the introduction of to_json, json_build_object, json_object and json_build_array, though it's verbose due to the need to name all the fields explicitly: select json_build_object( 'id', u.id, 'name', u.name, 'email...
PostgreSQL
13,227,142
121
Using PostgreSQL 9.0, I have a group role called "staff" and would like to grant all (or certain) privileges to this role on tables in a particular schema. None of the following work GRANT ALL ON SCHEMA foo TO staff; GRANT ALL ON DATABASE mydb TO staff; Members of "staff" are still unable to SELECT or UPDATE on the i...
You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies: (but note that ALL TABLES is considered to include views and foreign tables). Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual: For seq...
PostgreSQL
10,352,695
121
I need to document an API written in pure Flask 2 and I'm looking for what is a consolidated approach for doing this. I found different viable solutions but being new to Python and Flask I'm not able to choose among them. The solutions I found are: https://github.com/marshmallow-code/apispec https://github.com/jmcarp/...
Following the suggestion of migrating from Flask to FastAPI I gave it a try and rewrote the Flask-Example of the question. The source code is also available on GitHub. The structure of the project is almost identical, with some additional features available(e.g. the CORS Middleware): The models of the domain are sligh...
OpenAPI
67,849,806
14
With org.openapitools:openapi-generator-maven-plugin, I have noticed that using allOf composed of multiple objects in a response does not generate a class combining these multiple objects. Instead it uses the first class defined in the allOf section. Here is a minimal example (openapi.yaml) : openapi: 3.0.0 info: tit...
Version 6.0.0 of openapi-generator-maven-plugin solves the issue by generating a class (Get200Response) composed of the two objects A and B. After generating the classes using: mvn org.openapitools:openapi-generator-maven-plugin:6.0.0:generate \ -Dopenapi.generator.maven.plugin.inputSpec=openapi.yaml \ -Dopenap...
OpenAPI
68,773,761
14
I have an API that I created in .NetCore 3.1 and have enabled Swagger(OAS3) using Swashbuckle. By default when my app starts if brings up the Swagger page using this URL: http://{port}/swagger.index.html I would like to customize the Swagger URL so that it includes the name of the application that is running. The re...
I found the solution to this issue: In the Configure section of Startup.cs I did the following: First I added the folowing variable: private readonly string swaggerBasePath = "api/app"; Next I configured the path using UseSwagger and UseSwaggerUI to use the swaggerBasePath variable: app.UseSwagger(c => ...
OpenAPI
62,376,063
14
Springdoc automatically generates a API documentation for all handler methods. Even if there are no OpenAPI annotations. How can I hide endpoints from the API documentation?
The @io.swagger.v3.oas.annotations.Hidden annotation can be used at the method or class level of a controller to hide one or all endpoints. (See: https://springdoc.org/faq.html#how-can-i-hide-an-operation-or-a-controller-from-documentation) Example: @Hidden // Hide all endpoints @RestController @RequestMapping(path = "...
OpenAPI
62,102,261
14
I have a data model definition in OpenAPI 3.0, using SwaggerHub to display the UI. I want one of the properties of a model to be related, which is an array of properties of the same model. Foo: properties: title: type: string related: type: array items: ...
Your definition is correct, it's just Swagger UI currently does not render circular-referenced definitions properly. See issue #3325 for details. What you can do is add a model example, and Swagger UI will display this example instead of trying to generate an example from the definition. Foo: type: object ...
OpenAPI
50,950,278
14
I am writing an OpenAPI (Swagger) definition where a query parameter can take none, or N values, like this: /path?sort=field1,field2 How can I write this in OpenAPI YAML? I tried the following, but it does not produce the expected result: - name: sort in: query schema: type: string enum: [field1,field2,fie...
A query parameter containing a comma-separated list of values is defined as an array. If the values are predefined, then it's an array of enum. By default, an array may have any number of items, which matches your "none or more" requirement. If needed, you can restrict the number of items using minItems and maxItems, a...
OpenAPI
50,538,138
14
I am adding swagger UI to my Spring boot application. When I try to access the swagger-ui.html. I get the 404 error. Config class : @Configuration public class SwaggerConfig { @Bean public OpenAPI springShopOpenAPI() { return new OpenAPI() .info(new Info().title("JOYAS-STOCK API Docs") ...
Resolved. the issue was in the versions, they were not compatible! i was using springdoc-openapi v1 with spring boot 3. which is wrong! with spring boot 3, springdoc-openapi v2 should be used. see documentation : https://springdoc.org/v2/
OpenAPI
74,776,863
13
This is my FastAPI main.py file. from fastapi import FastAPI from project.config.settings import base as settings app = FastAPI(docs_url=f"{settings.URL_ROOT}/{settings.DOCS_URL}", redoc_url=None) app.openapi_version = "3.0.0" # some functions here And I deployed this project to a server. But when I go to address of...
You should check this page for proxy settings. but as far as i understand, you can fix this by just adding root_path to openapi_url: app = FastAPI( docs_url=f"/url_root/docs_url", openapi_url="/url_root/openapi.json", redoc_url=None)
OpenAPI
71,171,535
13
Consider this OAS3 spec (testMinMax3.yaml): openapi: 3.0.1 info: title: OpenAPI Test description: Test license: name: Apache-2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.0 servers: - url: http://localhost:9999/v2 paths: /ping: post: summary: test description: t...
No. minLength and required are separate constraints. minLength means that if a string value is provided, its length must be minLength or more.
OpenAPI
67,812,850
13
I want to have a description for RequestBody in spring boot openapi 3 . so i make my code like this : @PostMapping(produces = "application/json", consumes = "application/json") public ResponseEntity<Book> addBook( @Schema( description = "Book to add.", required=tr...
From your Code Snippet it seems to me as if your description actually belongs into the @RequestBody Annotation instead of the @Schema Annotation. With @Schema you define and describe your Models but what you actually want to do is to describe the parameter in the context of your operation. Try something along the lines...
OpenAPI
64,645,528
13
I would like the OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) to be able to generate Pageable parameter in API according to the implementation in Spring Boot Data. I've been trying to find a suitable, out of the box solution, but couldn't find one. Ideally, this Pageable parameter should be add...
Unfortunately this is no final solution but it is half way. Maybe it is of help anyway. By defining the pageable parameters (size, page etc.) as an object query parameter it is possible to tell the generator to use the Spring object instead of generating a Pageable class from the api. This is done by an import mapping....
OpenAPI
61,307,411
13
FastAPI automatically generates a schema in the OpenAPI spec for UploadFile parameters. For example, this code: from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(..., description="The file")): return {"filename": file.file...
I answered this over on FastAPI#1442, but just in case someone else stumbles upon this question here is a copy-and-paste from the post linked above: After some investigation this is possible, but it requires some monkey patching. Using the example given here, the solution looks like so: from fastapi import FastAPI, Fil...
OpenAPI
60,765,317
13
The documentation for defining general API information using the quarkus-smallrye-openapi extension is extremely sparse, and does not explain how to use all the annotations for setting up the openApi generation. For some background, I am using a clean and largely empty project (quarkus version1.0.1.FINAL) generated fro...
Try putting the annotation on the JAX-RS Application class. I realize you don't need one of those in a Quarkus application, but I think it doesn't hurt either. For reference in the specification TCK: https://github.com/eclipse/microprofile-open-api/blob/master/tck/src/main/java/org/eclipse/microprofile/openapi/apps/a...
OpenAPI
59,168,710
13
The DRF docs mention this: Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the the list and retrieve views, use docstring sections as described in Schemas as documentation: Examples. But the link is bad, and the similar link, ...
I came here from Google after spending ages tracking this down. There is indeed a special formatting of the docstring to document individual methods for ViewSets. The relevant example must have been removed from the documentation at some point but I was able to track this down in the source. It is handled by the functi...
OpenAPI
57,367,230
13
I can't find a sample of currency data type in the object definition, nor a document on the subject.
There is no built-in "currency" type. You would typically use type: number with an optional format modifier to indicate the meaning of the numeric type: type: number format: currency format can have arbitrary values, so you can use format: currency or format: decimal or whatever your tool supports. Tools that recogniz...
OpenAPI
46,350,701
13
Due to some backward compatibility reasons, I need to support both the paths /ab and /a-b. The request and response objects are going to be the same for both of the paths. Can I have something like the following in my Swagger spec so that I do not have to repeat the request and response object definitions for both the ...
Yes, you can have a path item that references another path item: paths: /ab: post: summary: ... ... responses: ... /a-b: $ref: '#/paths/~1ab' # <------------ Here, ~1ab is an encoded version of /ab (see below). One limitation of this approach is that you cannot have operationId...
OpenAPI
44,150,758
13
petstore_auth: type: oauth2 authorizationUrl: http://swagger.io/api/oauth/dialog flow: implicit scopes: write:pets: modify pets in your account read:pets: read your pets This is a securityDefinitions example from the Swagger Specification. What does the write:pets and read:pets intended for? Is that so...
write:pets and read:pets are Oauth2 scopes and are not related to OpenAPI (fka. Swagger) operations categorization. Oauth2 scopes When an API is secured with Oauth, scopes are used to give different rights/privilege to the API consumer. Scopes are defined by a name (you can use whatever you want). Oauth scopes authoriz...
OpenAPI
38,371,355
13
The @nestjs/swagger doc describes here that defining an extra model should be done this way: @ApiExtraModels(ExtraModel) export class CreateCatDto {} But what is ExtraModel here ? The doc is not very clear about this.
Worked for me, when I've set @ApiExtraModels(MyModelClass) on the top of controller. Thanks for this topic and also to this comment in GitHub issue. I don't want to list all models in extraModels array in SwaggerModule.createDocument, so this is a great solution for me.
OpenAPI
61,143,316
12
I'm using drf_yasg for swagger documentation. When I publish my DRF app behind AWS Application Load Balancer and set listener to listen on 443 HTTPS and redirect to my EC2 on which DRF is running, swagger UI is trying to send a request to endpoint http://example.com/status rather than e.g. https://example.com/status. T...
Add these in your Django settings.py # Setup support for proxy headers USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
OpenAPI
58,013,545
12
We have some Azure Functions exposed through Api Management? Can Api Management expose a /swagger endpoint automatically, the same way the Swashbuckle package does for api's in Asp.Net.
Azure API management cannot automatically generate the swagger page. Azure API management only can provide you the API definition file. Then you can use other tools (such as Swagger UI) with the definition file to generate the page you need. Besides, Azure API management has provided you the UI(https://youapimanagement...
OpenAPI
56,027,231
12
I have some model definition inside a XSD file and I need to reference these models from an OpenApi definition. Manually remodeling is no option since the file is too large, and I need to put it into a build system, so that if the XSD is changed, I can regenerate the models/schemas for OpenApi. What I tried and what ne...
I ended up implementing the second approach using jaxb to convert the XSD to java models and then using Jackson to write the schemas to files. Gradle: plugins { id 'java' id 'application' } group 'foo' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { t...
OpenAPI
56,018,335
12
I am currently migrating our API docs (which were Swagger 1.5) to Swagger 2.0 (OpenApi 3.0) The API docs are Swagger docs which get generated with java annotations using maven packages swagger-annotations and swagger-jaxrs. I have already updated the pom.xml with new versions so it looks like: <dependency> ...
After some research, I could find some documentation about it in their Github for JAX-RS application, so the result is something similar to what I was doing but now instead of using a BeanConfig, it uses OpenAPI and Info: @ApplicationPath("/sample") public class MyApplication extends Application { public MyApplica...
OpenAPI
54,185,836
12
I have an endpoint with query parameters that use square brackets: GET /info?sort[name]=1&sort[age]=-1 Here, name and age are the field names from my model definition. How can I write an OpenAPI (Swagger) definition for these parameters?
It depends on which version of OpenAPI (Swagger) you use. OpenAPI 3.x The sort parameter can be defined an an object with the name and age properties. The parameter serialization method should be style: deepObject and explode: true. openapi: 3.0.0 ... paths: /info: get: parameters: - in: query ...
OpenAPI
48,491,688
12
I want to extend the "200SuccessDefault" response with a schema or example. paths: /home: ... responses: 200: $ref: '#/components/responses/200SuccessDefault' content: application/json: schema: type: array items: ...
You cannot extend a referenced response object. But, you can use a shared schema object and extend it utilizing allOf within schema. Inside allOf you can put: your $ref a new type extending your default response If you want to give an example of an entire extended response (JSON), just put it into "application/json"....
OpenAPI
72,868,180
11
I have an application which provides an API with JAX-RS (Java API for RESTful Web Services / JSR-311). For documentation purposes I provide an URL according to the OpenAPI-Specification, which is generated by Eclipse MicroProfile OpenAPI. Everything is working fine, except the descriptions of the methods and parameters...
I got it running with Eclipse Microprofile OpenAPI. I had to define my own OASFilter: public class JavadocOASDescriptionFilter implements OASFilter { @Override public void filterOpenAPI(final OpenAPI openAPI) { openAPI.getComponents().getSchemas().forEach(this::initializeSchema); openAPI.getPat...
OpenAPI
65,935,055
11
I have a class that one of the properties can be string or array of strings, not sure how should I define it in swagger @ApiProperty({ description: `to email address`, type: ???, <- what should be here? required: true, }) to: string | Array<string>; I tried @ApiProperty({ ...
Please try @ApiProperty({ oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string' } } ] }) Array<TItem> can be expressed in OpenAPI with {type: 'array', items: { type: TItem } }
OpenAPI
64,939,247
11
I have an OpenAPI 3.0 spec (in YAML format), and would like to generate Java code for the API. I want to do this as part of an automated build (preferably using Gradle), so I can create the service interface, and the implementation of the interface as part of an automated process. This working example shows how to do i...
I've now got this working (thanks to @Helen for help) The edits required were in build.grade. First I had to amend the build scripts to pull in a different dependency: buildscript { repositories { mavenCentral() } dependencies { classpath('io.swagger.codegen.v3:swagger-codegen-maven-plugin:...
OpenAPI
59,875,910
11
I need to define in OpenAPI a JSON response with an array. The array always contains 2 items and the first one is always a number and second one is always a string. [1, "a"] //valid ["a", 1] //invalid [1] //invalid [1, "a", 2] //invalid I've found out that JSON schema does support that by passing a list ...
You need OpenAPI 3.1 to define tuples precisely. In earlier versions, you can only define generic arrays without a specific item order. OpenAPI 3.1 Your example can be defined as: # openapi: 3.1.0 type: array prefixItems: # The 1st item - type: integer description: Description of the 1st item # The 2nd item ...
OpenAPI
57,464,633
11
I am writing a new API and documenting it using Swagger/OpenAPI. It seems to be a good standard to document error responses, that the developer can expect to encounter. But I cannot find any guide lines or best practices about Internal Server Error. Every path could in theory throw an unhandled exception. I do not expe...
The offical documentation shows an example for specifying all 5xx status codes in the responses section, but it does not go into details about the specific status code, or the message returned. It also mentions that the API specification should only contain known errors: Note that an API specification does not necessa...
OpenAPI
54,989,351
11
I've tried to add a nested array of arbitrary types. These are my annotations: * @OA\Property( * @OA\Schema( * type="array", * @OA\Items( * type="array", * @OA\Items(type={}) * ) * ), * description="bla bla bla" * )
I've found the solution: * @OA\Property( * type="array", * @OA\Items( * type="array", * @OA\Items() * ), * description="bla bla bla" * ) The issue was @OA\Schema
OpenAPI
53,947,062
11
In the OpenAPI 3.0 Specification, the root OpenAPI Object has the servers property which is an array of Server Objects. And the Path Item Object also allows an optional servers property. The description given in the Specification does not give a clear idea of how servers can be helpful. What is the significance of the ...
servers specifies one or more target servers for the API, in other words, the base URL for API calls. The endpoint paths (e.g. /users/{id}) are defined relative to these servers. Some APIs have a single target server; others may offer several servers, e.g. sandbox vs. production, or regional servers for different geogr...
OpenAPI
50,546,573
11
I'm trying to document an existing API that contains various endpoints whose authentication is optional. That is, more data is returned if the user is authorized than if they were not authorized. Could not find that explicitly in the OAspec v3. Is there a coding trick to define this situation? My present work-around ...
To make security optional, add an empty requirement {} to the security array: security: - {} # <---- - api_key: [] This means the endpoint can be called with or without security. Source: this comment in the OpenAPI Spec repository.
OpenAPI
47,659,324
11
At the time of writing this the OpenAPI 3 spec is relatively new. I am struggling to find any documentation generators that support version 3.0. Does anyone know of generators that support OpenAPI v3.0?
You can try OpenAPI Generator (https://openapi-generator.tech), which supports both OpenAPI spec v2, v3 and released a stable version (3.0.0) a few days ago. Using docker, you can easily generate the API documentation: docker run --rm -v ${PWD}:/local openapitools/openapi-generator-cli generate \ -i https://raw.git...
OpenAPI
46,290,950
11
I have generated my API client with openapi-generator-cli generate -i https://linktomybackendswagger/swagger.json -g typescript-axios -o src/components/api --additional-properties=supportsES6=true Now I have all the files inside my project but I have no clue how to implement this. How do I instantiate the API? Where do...
Ok, so I figured out a way that I think is clean that I will document here for others that are going down the same path, which is: Using an API that is using Authorization: Bearer <Token here> Created the client with openapi-generator-cli using -g typescript-axios Using OAS3 Let's say you have an endpoint called User...
OpenAPI
70,185,507
10
I do have my .net data classes, containing a few decimal fields (for example quantity). I generate an openapi.json out of it running dotnet swagger. ... "quantity": { "type": "number", "format": "double" }, ... As you can see it produces a type "number" with format "double". And nswag...
Try adding this line into your .AddSwaggerGen() definition services.AddSwaggerGen(c => c.MapType<decimal>(() => new OpenApiSchema { Type = "number", Format = "decimal" }); // ...
OpenAPI
69,523,654
10
I use OpenAPI spec to generate Java POJOs. What do I need to specify in Open API yaml to generate the equivalent of below POJO ? ... @JsonIgnore public String ignoredProperty; ... I have the yaml spec as below openapi: 3.0.0 info: title: Cool API description: A Cool API spec version: 0.0.1 servers: - url: http...
the openapi generator supports vendor extensions. Specifically, for the Java generator, it supports the following extensions as of the time of writing. However, an up-to-date list can be found here. Extension name Description Applicable for Default value x-discriminator-value Used with model inheritance to sp...
OpenAPI
64,898,455
10
Swagger documentation says you can do that: https://swagger.io/docs/specification/grouping-operations-with-tags/ But unfortunately drf-yasg not implementing this feature: https://github.com/axnsan12/drf-yasg/issues/454 It is said, that I can add custom generator class, but it is a very general answer. Now I see that d...
Not sure if this is exactly what your are looking for, but I think it might help. To set tags I use @swagger_auto_schema decorator, which can be applied in a few different ways depending mostly on the type of Views used on your project. Complete details can be found on docs here. When using Views derived from APIView, ...
OpenAPI
62,572,389
10
What is the actual advantage of using OpenApi over swagger? I am new to openApi technology, just wanted to know what more features are present in openApi than in swagger. The online documents didn't helped me. Can anyone help me.
OpenApi is essentially a further development of swagger, hence the version 3.0.0 instead of 1.0.0 If you read the swagger blog Swagger was handed over to the OpenAPI Initiative, and all the swagger tools like editor.swagger.io support openapi, and conversions between the two. as they write OpenAPI = Specification Sw...
OpenAPI
61,019,331
10
Before Swashbuckle 5 it was possible to define and register a ISchemaFilter that could provide an example implementation of a model: public class MyModelExampleSchemaFilter : ISchemaFilter { public void Apply(Schema schema, SchemaFilterContext context) { if (context.SystemType.IsAssignableFrom(typeof(My...
They have an example on the repo: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/9bb9be9b318c576d236152f142aafa8c860fb946/test/WebSites/Basic/Swagger/ExamplesSchemaFilter.cs#L8 public class ExamplesSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) ...
OpenAPI
60,515,825
10
I have an endpoint to create an address and one to update it. Describing this in an OpenAPI spec I'd like to use a component for the address so that I don't have to specify the address twice. Now the problem is, that the address object used for updating should include a property "id", but the one used for creating does...
You can accomplish this using the readOnly keyword, which provides a standardized method to achieve the desired outcome. You can use the readOnly and writeOnly keywords to mark specific properties as read-only or write-only. This is useful, for example, when GET returns more properties than used in POST – you can use ...
OpenAPI
60,472,631
10
I am looking for the proper way to specify an Authorization header with a custom type/prefix like "ApiKey" in OpenAPI 3. The custom Authorization header should look like Authorization: ApiKey myAPIKeyHere All my attempts to specify the securitySchemes entry with type: apiKey seems to produce other results... The close...
I think I have found a way that seems acceptable - although not perfect. Would like to see something better in the future... It seems that there is no other way than to add the custom type to the value (aided by a description like below). components: securitySchemes: ApiKey: type: apiKey name...
OpenAPI
59,694,733
10
OpenAPI is good for RESTful services and at the moment, I'm hacking it to do it for asynchronous messaging system (specifically Kafka) by using POST to a /topic so that I can use redoc do create a website for the API. I am trying to see if there's already established system of documenting for this. Especially since th...
It seems asyncAPI is basically what you are looking for: openapi but for topics instead of REST endpoints. https://www.asyncapi.com/docs/getting-started/coming-from-openapi/
OpenAPI
59,143,626
10
This is my code: definitions: User: type: object properties: id: type: integer username: type: string first_name: type: string last_name: type: string password: type: string created_at: type: string format: date-time ...
As explained in this answer to a similar question: You would have to define the models separately. However, you have options for the cases of exclusion and difference. If you're looking to exclude, which is the easy case, create a model of with the excluded property, say ModelA. Then define ModelB as ModelA plus ...
OpenAPI
57,339,131
10
I'm trying to make an OpenAPI autogenerated PHP client using anyOf and allOf properties. The goal is to be able to return an array with polymorphism in it: objects of different types. Also those objects have a common base object as well. In my example schema, Items is an array which items can be of types ItemOne or Ite...
After more researching I found there's an open issue with the inheritance in the openapi-generator from version 4.0.0 onwards. https://github.com/OpenAPITools/openapi-generator/issues/2845
OpenAPI
57,313,269
10
I have my swagger definition like : someDef: type: object properties: enable: type: boolean default: false nodes: type: array maxItems: 3 items: type: object properties: ip: type: string default: '' ...
"Either 0 or 3 items" can be defined in OpenAPI 3.x (openapi: 3.x.x) but not in OpenAPI 2.0 (swagger: '2.0'). OpenAPI 3.x You can use oneOf in combination with minItems and maxItems to define the "either 0 or 3 items" condition: # openapi: 3.0.0 nodes: type: array items: type: object properties: ip: ...
OpenAPI
57,035,988
10
I have my openapi: 3.0.0 YAML file, I'm looking for a way to generate test data response (JSON object) from schema. This is what I am looking for, but I can't get it working for openapi: 3.0.0, the code works perfectly for "swagger": "2.0" definitions. I have tried to get the code working with Swagger Java libraries 2....
import io.swagger.v3.parser.OpenAPIV3Parser; import io.swagger.v3.oas.models.media.Schema; import io.swagger.oas.inflector.examples.models.Example; import io.swagger.oas.inflector.examples.ExampleBuilder; import com.fasterxml.jackson.databind.module.SimpleModule; import io.swagger.oas.inflector.processors.JsonNodeExamp...
OpenAPI
55,978,052
10
I have a new OpenAPI setup via SwaggerHub. Is there an option to force a certain Accept header globally? I have set up the Content-Type on the response: openapi: 3.0.0 paths: /test-path: get: responses: '200': description: OK content: application/vnd.company.v1...
Unlike OpenAPI/Swagger 2.0, which has global consumes and produces, OpenAPI 3.0 requires that request and response media types be defined in each operation individually. There's no way to define the Content-Type or requests or responses globally. You can, however, $ref common response definitions (such as error respons...
OpenAPI
54,145,884
10
I'm use L5-Swagger 5.7.* package (wrapper of Swagger-php) and tried describe Laravel REST API. So, my code like this: /** * @OA\Post(path="/subscribers", * @OA\RequestBody( * @OA\MediaType( * mediaType="application/json", * @OA\Schema( * type="object", * ...
The response(s) didn't specify a mimetype. @OA\Response(response=201, description="Successful created"), If you specify a json response, swagger-ui will send an Accept: application/json header. PS. Because json is so common swagger-php has a @OA\JsonContent shorthand, this works for the response: @OA\Response(respons...
OpenAPI
53,168,311
10
Swagger UI refuses to make a request to https with self signed certificate. The problem is next: curl -X POST "https://localhost:8088/Authenticate" -H "accept: pplication/json" -H "Content-Type: application/json" -d "{ \"username\":"user\", \"password\": \"user\"}" Above command is generated by swagger automatically a...
Firstly, the cURL command is for display and copy-pasting only. Swagger UI does not actually use cURL for requests – it's a web page so it makes requests using JavaScript (fetch API or XMLHttpRequest or similar). As explained here, Swagger UI does not support self-signed certificates (emphasis mine): It appears you ha...
OpenAPI
49,997,748
10