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
This question is about Redis persistence. I'm using redis as a 'fast backend' for a social networking website. It's a single server set up. I've been transferring PostgreSQL responsibilities to Redis steadily. Currently in etc/redis/redis.conf, the appendonly setting is set to appendonly no. Snapshotting settings are ...
Does this mean that practically, I'm getting backups every 60 seconds? NO. Redis does a background save after 60 seconds, if there're at least 10000 keys have been changed. Otherwise, it doesn't do a background save. Will using appendonly on and appendfsync everysec cause a performance downgrade? Will it hit the CPU...
Redis
39,953,542
31
TL;DR: which of the three options below is the most efficient for paginating with Redis? I'm implementing a website with multiple user-generated posts, which are saved in a relational DB, and then copied to Redis in form of Hashes with keys like site:{site_id}:post:{post_id}. I want to perform simple pagination queries...
"Best" is best served subjective :) I recommend you go with the 2nd approach, but definitely use Sorted Sets over Lists. Not only do the make sense for this type of job (see ZRANGE), they're also more efficient in terms of complexity compared to LRANGE-ing a List.
Redis
32,076,783
31
What are the steps required to set up Redis database on Webfaction shared hosting account?
Introduction Because of the special environment restrictions of Webfaction servers the installation instructions are not as straightforward as they would be. Nevertheless at the end you will have a fully functioning Redis server that stays up even after a reboot. I personally installed Redis by the following procedure ...
Redis
18,622,630
31
I'm using Resque workers to process job in a queue, I have a large number of jobs > 1M in a queue and have some of the jobs that I need to remove ( added by error). Crating the queue with the jobs was not an easy tasks, so clearing the queue using resque-web and adding the correct jobs again is not an option for me. Ap...
In resque's sources (Job class) there's such method, guess it's what you need :) # Removes a job from a queue. Expects a string queue name, a # string class name, and, optionally, args. # # Returns the number of jobs destroyed. # # If no args are provided, it will remove all jobs of the class # provided. # # That is, f...
Redis
10,274,974
31
I have installed redis. The default given name to me is plinking-narwhal. Now I would like to install a service with my assigned name. But first I want to remove the existing one. I had tried deleting them without success. $ kubectl get all NAME READY STATUS RESTARTS...
You probably need: $ helm delete redis or if you completely want to remove the release: $ helm delete redis --purge stable/redis is not allowed as an expression because of the slash(/) If you'd like to see the name of the releases you can simply run: $ helm list -aq
Redis
55,036,464
30
When using node_redis Node.js module with Redis, should I just use one connection as Redis is single thread process or shall I create a pool of connections to improve performance?
Just use a single connection. Both Node and Redis are effectively single thread. I don't think you'll gain anything by having multiple connections. I asked a similar question before starting to develop with Redis and it seems that one client/one application is pretty effective pattern. Highlighting an important note fr...
Redis
21,976,270
30
In redis-cli, what is the command to print all the values in a list without knowing in advance the size of the list? I see lrange, but it requires naming the start index and the end index.
You use -1 to indicate end of list so: LRANGE key 0 -1 would print all.
Redis
20,829,778
30
I need to see all available keys in Redis. This question: Redis command to get all available keys? Adequately covers the case where I run redis-cli with no arguments, then type keys *. However, how do I get all keys with a single command? redis-cli keys * returns: (error) ERR wrong number of arguments for 'keys' comm...
You need to do redis-cli keys '*' to avoid your shell from expanding * into a list of filenames.
Redis
12,119,075
30
I know the KEYS command, but that only returns the keys (I'm guessing all of the keys with type String), and apparently sets aren't considered keys. Is there a command for getting all of the sets in the database? What about other data types (hash, list, sorted set)? http://redis.io/topics/data-types
I know the KEYS command, but that only returns the keys (I'm guessing all of the keys with type String), and apparently sets aren't considered keys. KEYS command return results no matter what data type are your keys, since it searches key names. At the lowest level of abstraction each data type in redis is key/va...
Redis
7,462,457
30
I'm getting more into Node.js and am enjoying it. I'm moving more into web application development. I have wrapped my head around Node.js and currently using Backbone for the front end. I'm making a few applications that uses Backbone to communicate with the server using a RESTful API. In Node.js, I will be using the E...
Is any one of them better suited for Node JS? Better suited especially for node.js probably no, but each of them is better suited for certain scenarios based on your application needs or use cases. Redis is an advanced key-value store and probably the fastest one among the three NoSQL solutions. Besides basic key d...
Redis
6,507,953
30
I'm currently migrating some data to Redis and I'm considering using a sorted set to store approximately 1.4e6 items (with associated scores/counts). Is this number of items in a set likely to exceed a practical limit, making it too painful to use the set? I plan on running 64 bit redis, so available memory for the dat...
It depends what you want to do with the set. The simple operations are mostly O(log n) which means that they take only twice as long for a million item set as they do for a thousand item set. Unless you have something seriously broken in your config like a memory limit smaller than the set, performance shouldn't be a p...
Redis
6,076,342
30
I'm looking for a way to store a list of items for a user, that will expire within 24 hours. Is there a way to accomplish this using Redis? I was thinking of just using the list and setting an expiration for each individual item, is there a better way?
i use: ZADD - adding new unique value to sorted set. ZRANGE - get all current values ordered by score from the set. (ZREMRANGEBYSCORE has been deprecated) ZREMRANGEBYSCORE - remove all keys between scores from the set. in this solution the score = timestamp for example: 3 values insertion: ZADD mykey 160 val1 /...
Redis
48,044,721
29
I know that it is possible to pass your own config file but I'd rather edit the handful of values I care about in the default config. I'm having a hard time finding a default redis.conf anywhere though, do I just have to COPY my own into the container?
The default image from redis does not have a redis.conf. Here is the link for the image on dockerhub. https://hub.docker.com/_/redis/ You will have to copy it to image or have it mapped on the host using a volume mapping.
Redis
37,402,551
29
I've found different zookeeper definitions across multiple resources. Maybe some of them are taken out of context, but look at them pls: A canonical example of Zookeeper usage is distributed-memory computation... ZooKeeper is an open source Apache™ project that provides a centralized infrastructure and services tha...
https://zookeeper.apache.org/doc/current/zookeeperOver.html By default, Zookeeper replicates all your data to every node and lets clients watch the data for changes. Changes are sent very quickly (within a bounded amount of time) to clients. You can also create "ephemeral nodes", which are deleted within a specified ti...
Redis
37,293,928
29
When I run the command redis-cli INFO, one of the returned values indicates the avg_ttl. I'm unsure what unit of time this is represented in? Example: # Keyspace db0:keys=706818,expires=228745,avg_ttl=1521990750
This is a bit confusing indeed. the TTL command return value is in seconds PTTL command return value is in milliseconds avg_ttl from INFO is in milliseconds Also, note that this average value avg_ttl is just an estimate based on random check of keys.
Redis
26,226,588
29
I need to create a solution using php, with a mysql database with lots of data. My program will have many requisitions, I think that if I work with cache and an OO database, I'll have a good result, but I don't have experience. I think for example if I cache the information that is saved in mysql in a redis database, p...
Yes, redis is good for that. But to get the gist, there are basically two approaches to caching. Depending on whether you use a framework (and which) or not, you may have first option available in standard or with use of a plug-in: Cache database queries, that is - selected queries and their results will be kept in re...
Redis
16,268,950
29
I'm using node_redis and I'd like to save a structure like: { users : "alex" : { "email" : "alex@gmail.com", "password" : "alex123"}, "sandra" : { "email" : "sandra@gmail.com", "password" : "sandra123"}, ... } Currently, for each user I create a JSON object: jsonObj = { "email" : "al...
As far as I know there isn't native support for nested structures in Redis, but they can be modeled for example with set+hash (similar to hierarchical trees). Hashes are probably best suited for storing fields and values of single JSON object. What I would do is to store each user with a prefix (which is a Redis conven...
Redis
5,701,491
29
Question is about keeping Redis data alive between docker-compose up and docker-compose down. In the docker-compose.yaml file bellow db service uses - postgres_data:/var/lib/postgresql/data/ volume to keep data alive. I would like to do something like this for redis service but I can not find workable solution to...
You just need to add a named volume for Redis data next to the postgres_data: volumes: postgres_data: redis_data: Then change host path to the named volume: redis: ... volumes: - redis_data:/data If Redis saved data with host path, then the above will work for you. I mention that because you...
Redis
63,906,856
28
Using dd = {'ID': ['H576','H577','H578','H600', 'H700'], 'CD': ['AAAAAAA', 'BBBBB', 'CCCCCC','DDDDDD', 'EEEEEEE']} df = pd.DataFrame(dd) Pre Pandas 0.25, this below worked. set: redisConn.set("key", df.to_msgpack(compress='zlib')) get: pd.read_msgpack(redisConn.get("key")) Now, there are deprecated warning...
Here's a full example to use pyarrow for serialization of a pandas dataframe to store in redis apt-get install python3 python3-pip redis-server pip3 install pandas pyarrow redis and then in python import pandas as pd import pyarrow as pa import redis df=pd.DataFrame({'A':[1,2,3]}) r = redis.Redis(host='localhost', po...
Redis
57,949,871
28
I have installed and compiled Redis from source and am attempting to connect to an Amazon ElastiCache (Redis) cluster. I can connect to the default localhost with no problem, but attempting to connect to an AWS endpoint causes what seems to be an infinite hangup. With defaults: $ redis-server /etc/redis.conf # daemoni...
I was also seeing the call to redis-cli hang up infinitely, but in my case it did not stem from incorrectly-configured security groups. Instead, it occurred because I had created my Redis cluster with the 'Encryption in-transit' option set to 'Yes'. This meant my database endpoint needed to be accessed through an SSL t...
Redis
52,043,233
28
On a fresh Ubuntu 16.04 EC2 instance the warnings appear like so: WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. W...
Like the warning suggests, just add the line vm.overcommit_memory=1 to the bottom of /etc/sysctl.conf, with something like sudo vi /etc/sysctl.conf. But permissions don't allow you to edit THP as the warning suggests, so instead do sudo apt install hugepages and add the command sudo hugeadm --thp-never to the bottom ...
Redis
41,203,492
28
I cache some data in redis, and reading data from redis if it's exists, otherwise reading data from database and write the data in redis. I find that there are several ways to update redis after updating database.For example: set keys in redis to expired update redis immediately after updating datebase. put data in MQ...
Actual data store and cache should be synchronized using the third approach you've already described in your question. As you add data to your definitive store (i.e. your SQL database), you need to enqueue this data to some service bus or message queue, and let some asynchronous service do the whole synchronization usi...
Redis
36,302,972
28
In Redis, keys user* will print all keys starting with user. For example: keys user* 1) "user2" 2) "user1" Now, I want all keys that don't start with user to be printed. How could I do that?
IMPORTANT: always use SCAN instead of (the evil) KEYS Redis' pattern matching is somewhat functionally limited (see the implementation of stringmatchlen in util.c) and does not provide that which you seek ATM. That said, consider the following possible routes: Extend stringmatchlen to match your requirements, possibl...
Redis
29,942,541
28
What is a zset in a redis database. I have a redis database with some data. In order to get the values KEYS *apple* 1) "compleet-index:products:apple" 2) "compleet-index:brands:apple" after to get the key GET compleet-index:productos:apple and I had the response (error) WRONGTYPE Operation against a key holding th...
Short answer: Use ZRANGE compleet-index:products:apple 0 -1 WITHSCORES ZSET is a short name for Redis Sorted Set, a Redis data type documented here. Each key in a sorted set has multiple values inside, associated with a floating value score.
Redis
29,800,178
28
I need to install redis in amazon cloud. I need it as a part of my npm module kue (deployment). Can anyone link me step by step tutorial or explain how to do it, considering the fact that I'm not good to bad with linux and administration.
If you enable the Extra Packages for Enterprise Linux (EPEL) repository that's present on Amazon Linux, you can install with yum. sudo yum-config-manager --enable epel sudo yum install redis # Start redis server sudo redis-server /etc/redis.conf
Redis
27,690,142
28
I have this code to add object and index field in Stackexchange.Redis. All methods in transaction freeze thread. Why ? var transaction = Database.CreateTransaction(); //this line freeze thread. WHY ? await transaction.StringSetAsync(KeyProvider.GetForID(obj.ID), PreSaveObject(obj)); await transaction.HashSetAs...
Commands executed inside a transaction do not return results until after you execute the transaction. This is simply a feature of how transactions work in Redis. At the moment you are awaiting something that hasn't even been sent yet (transactions are buffered locally until executed) - but even if it had been sent: res...
Redis
25,976,231
28
I was able to do this in ServiceStack.redis by using, IRedisTypedClient<ObjectName> myObj = redisClient.As<ObjectName>(); But I couldn't find any examples to do this in StackExchange.Redis. Do I have to Serialize to JSON and then store them? Thanx in advance.
At the current time, SE.Redis does not attempt to offer serialisation - there are simply too many different ways of doing that. I'm rather of the opinion that the library should do one thing, not 7. It should be possible to add any hybrid serialisation etc concerns simply by extension methods or other plumbing/wrapping...
Redis
25,536,312
28
I have a Flask app that takes parameters from a web form, queries a DB with SQL Alchemy and returns Jinja-generated HTML showing a table with the results. I want to cache the calls to the DB. I looked into Redis (Using redis as an LRU cache for postgres), which led me to http://pythonhosted.org/Flask-Cache/. Now I am t...
You don't need to create custom RedisCache class. The docs is just teaching how you would create new backends that are not available in flask-cache. But RedisCache is already available in werkzeug >= 0.7, which you might have already installed because it is one of the core dependencies of flask. This is how I could run...
Redis
24,589,123
28
I am a novice in using Redis DB. After reading some of the documentation and looking into some of the examples on the Internet and also scanning stackoverflow.com, I can see that Redis is very fast, scales well but this costs the price that we have to think out how our data will be accessed at the design time and what ...
Redis is for use cases where you need to access and update data at very high frequency and where you benefit from use of data structures (hashes, sets, lists, strings, or sorted sets). It's made to fill very specific use cases. If you have a general use case like very flexible searching, you'd be much better served by ...
Redis
17,193,176
28
I've been using PostgreSQL for the longest time. All of my data lives inside Postgres. I've recently looked into redis and it has a lot of powerful features that would otherwise take a couple of lines in Django (python) to do. Redis data is persistent as long the machine it's running on doesn't go down and you can conf...
Redis is increasingly used as a caching layer, much like a more sophisticated memcached, and is very useful in this role. You usually use Redis as a write-through cache for data you want to be durable, and write-back for data you might want to accumulate then batch write (where you can afford to lose recent data). Post...
Redis
17,033,031
28
Now that Stack Overflow uses redis, do they handle cache invalidation the same way? i.e. a list of identities hashed to a query string + name (I guess the name is some kind of purpose or object type name). Perhaps they then retrieve individual items that are missing from the cache directly by id (which bypasses a bu...
I honestly can't decide if this is a SO question or a MSO question, but: Going off to another system is never faster than querying local memory (as long as it is keyed); simple answer: we use both! So we use: local memory else check redis, and update local memory else fetch from source, and update redis and local memo...
Redis
9,596,877
28
I am trying to scale a simple socket.io app across multiple processes and/or servers. Socket.io supports RedisStore but I'm confused as to how to use it. I'm looking at this example, http://www.ranu.com.ar/post/50418940422/redisstore-and-rooms-with-socket-io but I don't understand how using RedisStore in that code woul...
but I don't understand how using RedisStore in that code would be any different from using MemoryStore. Can someone explain it to me? The difference is that when using the default MemoryStore, any message that you emit in a worker will only be sent to clients connected to the same worker, since there is no IPC betwee...
Redis
9,267,292
28
I'm currently running multiple redis instances on one box. Each have their own config, init.d, and listen on different ports. My application(s) have no problem connecting via the redis clients, but I'd like to be able to connect to each one using redis-cli. I couldn't find any information on $:redis-cli [options] in ei...
You can specify the server host and port using -h and -p parameters. E.g.: redis-cli -h 127.0.0.1 -p 6379
Redis
6,206,971
28
Why does Redis, a datastore, have Pub/Sub features? My first thought is that it's the wrong layer to implement such a thing. But maybe I need to think outside the box.
Redis is defined as data structure server. Redis provides multiple functionality like memcache, queue, pubsub etc. This is very useful for a cloudapp/webstack where 3 components RabbitMQ(queuing) + XMPP(pubsub) + Memcache can be currently replaced with redis. Queuing is not as feature rich as RabbitMQ though.
Redis
4,938,520
28
Problem On my Ruby on Rails app, I keep getting the error below for the Heroku Redis Premium 0 add-on: OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed (self signed certificate in certificate chain) Heroku Redis documentation mentions that I need to enable TLS in my Redis ...
Solution Use OpenSSL::SSL::VERIFY_NONE for your Redis client. Sidekiq # config/initializers/sidekiq.rb Sidekiq.configure_server do |config| config.redis = { ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE } } end Sidekiq.configure_client do |config| config.redis = { ssl_params: { verify_mode: OpenSSL::SSL::VE...
Redis
65,834,575
27
I am trying to insert multiple key/values at once on Redis (some values are sets, some are hashes) and I get this error: ERR CROSSSLOT Keys in request don't hash to the same slot. I'm not doing this from redis-cli but from some Go code that needs to write multiple key/values to a redis cluster. I see other places in th...
In a cluster topology, the keyspace is divided into hash slots. Different nodes will hold a subset of hash slots. Multiple keys operations, transactions, or Lua scripts involving multiple keys are allowed only if all the keys involved are in hash slots belonging to the same node. Redis Cluster implements all the singl...
Redis
38,042,629
27
I tested all the transaction commands (MULTI, EXEC, WATCH, DISCARD) in redis-cli. But when i tried with redis-py the following error occurred: AttributeError: 'Redis' object has no attribute 'multi' I have tried the following code snippet: import redis,time r = redis.Redis() try: r.set("transError",10) r.wat...
In redis-py MULTI and EXEC can only be used through a Pipeline object. Try the following: r = redis.Redis() p = r.pipeline() p.set("transError", var) p.execute() With the monitor command through the redis-cli you can see MULTI, SET, EXEC sent when p.execute() is called. To omit the MULTI/EXEC pair, use r.pipeline(tran...
Redis
31,769,163
27
I am trying to insert a large(-ish) number of elements in the shortest time possible and I tried these two alternatives: 1) Pipelining: List<Task> addTasks = new List<Task>(); for (int i = 0; i < table.Rows.Count; i++) { DataRow row = table.Rows[i]; Task<bool> addAsync = redisDB.SetAddAsync(string.Format(keyFor...
Behind the scenes, SE.Redis does quite a bit of work to try to avoid packet fragmentation, so it isn't surprising that it is quite similar in your case. The main difference between batching and flat pipelining are: a batch will never be interleaved with competing operations on the same multiplexer (although it may be ...
Redis
27,796,054
27
I try to run Celery example on Windows with redis backend. The code looks like: from celery import Celery app = Celery('risktools.distributed.celery_tasks', backend='redis://localhost', broker='redis://localhost') @app.task(ignore_result=False) def add(x, y): return x + y @app.task(igno...
According to Celery 'Getting Started' not able to retrieve results; always pending and https://github.com/celery/celery/issues/2146 it is a Windows issue. Celery -P threads or --pool=solo options solves the issue.
Redis
27,357,732
27
I want to use Redis as a cache storage for multiple applications on the same physical machine. I know at least two ways of doing it: by running several Redis instances on different ports; by using different Redis databases for different applications. But I don't know which one is better for me. What are advantages an...
Generally, you should prefer the 1st approach, i.e. dedicated Redis servers. Shared databases are managed by the same Redis process and can therefore block each other. Additionally, shared databases share the same configuration (although in your case this may not be an issue since all databases are intended for caching...
Redis
27,217,502
27
How do I use Flask-Cache @cache.cached() decorator with Flask-Restful? For example, I have a class Foo inherited from Resource, and Foo has get, post, put, and delete methods. How can I can invalidate cached results after a POST? @api.resource('/whatever') class Foo(Resource): @cache.cached(timeout=10) def get...
As Flask-Cache implementation doesn't give you access to the underlying cache object, you'll have to explicitly instantiate a Redis client and use it's keys method (list all cache keys). The cache_key method is used to override the default key generation in your cache.cached decorator. The clear_cache method will clea...
Redis
24,816,799
27
I'm a newbie in some of the AWS services. I was following this documentation link: http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/GettingStarted.ConnectToCacheNode.Redis.html And I already installed redis-cli with brew in my computer(I'm in a mac) and I'm still having the same error when trying to connec...
You can't connect to eleasticache from outside of aws. It just the way it is setup. Would be nice to do for debugging and development, but for production it doesn't really make sense to introduce that much latency into a system that main purpose is to give as-fast-as-possible results. From AWS FAQ: Please note that IP...
Redis
22,723,812
27
I am currently using Redis for my app, and its features are really excellent for my application (lists, sets, sorted sets etc.). My application relies heavily on sorted sets, lists, sets. And their related functions (push to a list, get list, union of sets etc. The only problem I am facing right now is that my data is...
There are numerous on-disk databases with Redis-like datastructures or even trying to be drop-in protocol-compatible replacements for Redis. There are excellent recommendations in "Is there something like Redis DB, but not limited with RAM size?" - pity the community considers such questions to be off-topic. In partic...
Redis
15,362,076
27
Basic question: Using Node.js I would like to get all the keys in my redis db. My redis db looks like this when I call keys *; aXF x9U lOk So each record I have, has a unique key, generated as a random string. Now I would like to call something like foreach(key in Redis) and get all keys in the redis. Would it be pos...
Sure, you'll need to install the redis module for nodejs which can be found at https://github.com/redis/node-redis. npm install redis Then you would do: var redis = require('redis'), client = redis.createClient(); client.keys('*', function (err, keys) { if (err) return console.log(err); for(var i = 0, len...
Redis
12,793,938
27
I am using predis, it's subscribed to a channel and listening. It throws the following error (below) and dies after 60 secs exactly. It's surely not my web servers error or its timeout. There is a similar issue being discussed here. Could not get much of it. I tried setting connection_timeout in predis conf file to 0, ...
Just set the read_write_timeout connection parameter to 0 or -1 to fix this. e.g. $redis = new Predis\Client('tcp://10.0.0.1:6379'."?read_write_timeout=0"); Setting connection parameters is documented in the README. The author of Redis noted the relevance of the read_write_timeout parameter to this error in an issue o...
Redis
11,776,029
27
Hi all and thanks in advance. I am new to the NoSQL game but my current place of employment has tasked me with set comparisons of some big data. Our system has customer tag set and targeted tag sets. A tag is an 8 digit number. A customer tag set may have up to 300 tags but averages 100 tags A targeted tag set may have...
This is an interesting problem, and I think Redis can help here. Redis can store sets of integers using an optimized "intset" format. See http://redis.io/topics/memory-optimization for more information. I believe the correct data structure here is a collection of targeted tag sets, plus a reverse index to map tags to t...
Redis
11,095,331
27
I want to be able to run a callback when any change is made in my redis collection. The callback would take the key and value as inputs. Is something like this possible? Thanks?
UPDATE (2020): Whomever is reading this - these are ancient answers, disregard them all. What you need is Redis Keyspace Notifications which have been around for ages. See https://redis.io/topics/notifications
Redis
10,676,951
27
— I built a simple app that pulls in data (50 items) from a Redis DB and throws it up at localhost. I did an ApacheBench (c = 100, n = 50000) and I'm getting a semi-decent 150 requests/sec on a dual-core T2080 @ 1.73GHz (my 6 y.o laptop), but the proc usage is very disappointing as shown: Only one core is used, which ...
Actually, your workload is not really I/O bound: it is CPU bound due to the cost of jade-based dynamic page generation. I cannot guess the complexity of your jade template, but even with simple templates, generating HTML pages is expensive. For my tests I used this template: html(lang="en") head title Example b...
Redis
10,663,809
27
We have configured the Redis server with one master and two slaves. If my master fails, how can we handle the failover without restarting the Redis server.
Update: Today, I would recommend checking out redis-sentinel, a tool by Redis' author antirez for monitoring and automatic failover. Original reply: Check the SLAVEOF command: http://redis.io/commands/slaveof When you discover that your master fails, issue a SLAVEOF NO ONE on one of your slaves to promote it to master....
Redis
9,223,840
27
I have separated the data using a colon. redis> keys party:* 1) "party:congress:president" 2) "party:bjp:president" 3) "party:bjp" 4) "party:sena" Is there any command that will list of all the parties? In case of above example, I expect congress bjp sena
No, there is no command to do that. But it would be trivial to implement it on client side, if you really have to. Applications should never use the KEYS commands to retrieve data. KEYS blocks the whole Redis instance while it is scanning linearly the millions of keys you have stored. It is more a debugging command sup...
Redis
8,744,207
27
Lets say I have an object (User) which consists of a few properties (ID, Name, Surename, Age). Which way is better to store this object in redis? store each property value in dedicated key, for example user:{id}:id, user:{id}:name, user:{id}:surename, user:{id}:age store whole User object as JSON string in one key, fo...
According to these two sources probably the optimal solution would be to use hashes because of memory consumption when using dedicated keys and long string in scenario with JSON as key value.
Redis
5,252,456
27
What is Redis's database size to memory ratio? For instance, if I have an 80MB database, how much RAM will Redis use (when used with a normal web app)?
Redis will use a bit more RAM than disk. The dumpfile format is probably a bit more densely packed. This is some numbers from a real production system (a 64 bit EC2 large instance running Redis 2.0.4 on Ubuntu 10.04): $ redis-cli info | grep used_memory_human used_memory_human:1.36G $ du -sh /mnt/data/redis/dump.rdb ...
Redis
4,731,873
27
I am trying to convey that the authentication/security scheme requires setting a header as follows: Authorization: Bearer <token> This is what I have based on the swagger documentation: securityDefinitions: APIKey: type: apiKey name: Authorization in: header security: - APIKey: []
Maybe this can help: swagger: '2.0' info: version: 1.0.0 title: Bearer auth example description: > An example for how to use Bearer Auth with OpenAPI / Swagger 2.0. host: basic-auth-server.herokuapp.com schemes: - http - https securityDefinitions: Bearer: type: apiKey name: Authorization in...
OpenAPI
32,910,065
181
I have JSON schema file where one of the properties is defined as either string or null: "type":["string", "null"] When converted to YAML (for use with OpenAPI/Swagger), it becomes: type: - 'null' - string but the Swagger Editor shows an error: Schema "type" key must be a string What is the correct way to defin...
This depends on the OpenAPI version. OpenAPI 3.1 Your example is valid in OpenAPI 3.1, which is fully compatible with JSON Schema 2020-12. type: - 'null' # Note the quotes around 'null' - string # same as type: ['null', string] The above is equivalent to: oneOf: - type: 'null' # Note the quotes around 'null...
OpenAPI
48,111,459
176
What is the correct way to declare a date in a swagger-file object? I would think it is: startDate: type: string description: Start date example: "2017-01-01" format: date But I see a lot of declarations like these: startDate: type: string description: Start date example: "2017-01-01" ...
The OpenAPI Specification says that you must use: type: string format: date # or date-time The internet date/time standard used by OpenAPI is defined in RFC 3339, section 5.6 (effectively ISO 8601) and examples are provided in section 5.8. So for date values should look like "2018-03-20" and for date-time, "2018-03-20...
OpenAPI
49,379,006
160
I have an API reference in a Swagger file. I want to create a very simple mock server, so that when I call e.g.: mymockurl.com/users it will return a predefined JSON (no need to connect to a database). What's the easiest way to do this? I'm not a backend guy.
An easy way to create simple mock from an OpenAPI (fka Swagger) spec without code is to use a tool call prism available at http://github.com/stoplightio/prism written in Typescript. This command line is all you need: ./prism run --mock --list --spec <your swagger spec file> The mock server will return a dynamic respon...
OpenAPI
38,344,711
123
I am developing a REST API. during development I have used postman (chrome extension) to use and document my API. It is a wonderful tool and I have most of my API endpoints in it. However, as we near release I would like to document this API in swagger, how would I do that? Is there a way that I can generate swagger b...
As of 2022 my recommendation is the excellent Rust/Wasm tool from Kevin Swiber, which is available online, as a Rust crate and as an npm module. https://kevinswiber.github.io/postman2openapi/ APIMatic API Transformer can process a Postman collection (v1 or v2) as an input format and produce Swagger 1.2 or 2.0, and now ...
OpenAPI
31,299,098
118
When using JSON Schema and Open API specification (OAS) to document a REST API, how do I define the UUID property?
There's no built-in type for UUID, but the OpenAPI Specification suggests using type: string format: uuid From the Data Types section (emphasis mine): Primitives have an optional modifier property: format. OAS uses several known formats to define in fine detail the data type being used. However, to support documentat...
OpenAPI
50,204,588
113
How to I define in OpenAPI/Swagger if a field is optional or required and what is the default?
By default, fields in a model are optional unless you put them in the required list. Below is an example - id, category are optional fields, name is required. Note that required is not an attribute of fields, but an attribute of the object itself - it's a list of required properties. type: object required: # List the ...
OpenAPI
40,113,049
109
Let's say I've got a parameter like limit. This one gets used all over the place and it's a pain to have to change it everywhere if I need to update it: parameters: - name: limit in: query description: Limits the number of returned results required: false type: number format: int32 Ca...
This feature already exists in Swagger 2.0. The linked ticket talks about some specific mechanics of it which doesn't affect the functionality of this feature. At the top level object (referred to as the Swagger Object), there's a parameters property where you can define reusable parameters. You can give the parameter ...
OpenAPI
27,005,105
106
This question is not a duplicate of (Swagger - Specify Optional Object Property or Multiple Responses) because that OP was trying to return a 200 or a 400. I have a GET with an optional parameter; e.g., GET /endpoint?selector=foo. I want to return a 200 whose schema is different based on whether the parameter was pas...
OpenAPI 2.0 OAS2 does not support multiple response schemas per status code. You can only have a single schema, for example, a free-form object (type: object without properties). OpenAPI 3.x In OAS3 you can use oneOf to define multiple possible request bodies or response bodies for the same operation: openapi: 3.0.0 .....
OpenAPI
36,576,447
90
I am using Swagger to document my REST services. One of my services requires a CSV file to be uploaded. I added the following to the parameters section in my JSON API definition: { "name": "File", "description": "The file in zip format.", "paramType": "body", "required": true, "allowM...
OpenAPI Specification 2.0 In Swagger 2.0 (OpenAPI Specification 2.0), use a form parameter (in: formData) with the type set to file. Additionally, the operation's consumes must be multipart/form-data. consumes: - multipart/form-data parameters: - name: file in: formData # <----- description: T...
OpenAPI
14,455,408
82
There is a function in my REST web service working with GET method and it has two optional parameters. I tried to define it in Swagger but I encountered an error, Not a valid parameter definition, after I set the required as false. I found out that if I set the required value as true the error will be gone. Here is a ...
Given that path parameter must be required according to the OpenAPI/Swagger spec, you can consider adding 2 separate endpoints with the following paths: /get/{param1}/{param2} when param2 is provided /get/{param1}/ when param2 is not provided
OpenAPI
35,011,192
76
Is there a generator to convert OpenAPI 3.0 to Swagger 2.0? Mashery, an API gateway, requires Swagger 2.0 format on input to open endpoint.
LucyBot api-spec-converter (online version, GitHub repo, Node.js module) can convert from OpenAPI 3.0 to 2.0. API Transformer (paid service) also claims to be able to convert OpenAPI 3.0 back to OpenAPI 2.0. It has a command-line version too. Keep in mind that OAS3→OAS2 convertion is lossy in general, because OAS3 ...
OpenAPI
56,637,299
76
Given the following OpenAPI definition Person: required: - id type: object properties: id: type: string Which of the below objects are valid? Only A, or A & B? A. {"id": ""} B. {"id": null} C. {} This boils down to the question whether "required = true" means "non-null value" or "property must be...
The required keyword in OpenAPI Schema Objects is taken from JSON Schema and means: An object instance is valid against this keyword if every item in the [required] array is the name of a property in the instance. In other words, required means "property must be present", regardless of its value. The type, format, et...
OpenAPI
45,575,493
68
I try to follow these: https://www.dariawan.com/tutorials/spring/documenting-spring-boot-rest-api-springdoc-openapi-3/ How do I deal with annotations like: @ApiModel(value = "Response container") @ApiModelProperty(value = "Iventory response", required = true)
Migrating from SpringFox Remove springfox and swagger 2 dependencies. Add springdoc-openapi-ui dependency instead. <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>@springdoc.version@</version> </dependency> Replace swagger 2 annotations wi...
OpenAPI
59,291,371
68
I'm currently using Swagger in my NestJS project, and I have the explorer enabled: in main.js const options = new DocumentBuilder() .setTitle('My App') .setSchemes('https') .setDescription('My App API documentation') .setVersion('1.0') .build() const document = SwaggerModule.createDocument(app, opt...
Securing access to your Swagger with HTTP Basic Auth using NestJS with Express First run npm i express-basic-auth then add the following to your main.{ts,js}: import * as basicAuth from "express-basic-auth"; // ... // Sometime after NestFactory add this to add HTTP Basic Auth app.use( // Paths you want to protect w...
OpenAPI
54,802,832
65
I'm using http://editor.swagger.io to design an API and I get an error which I don't know how to address: Schema error at paths['/employees/{employeeId}/roles'].get.parameters[0] should NOT have additional properties additionalProperty: type, format, name, in, description Jump to line 24 I have other endpoints defined...
The error message is misleading. The actual error is that your path parameter is missing required: true. Path parameters are always required, so remember to add required: true to them.
OpenAPI
45,549,663
64
I am familiar with the Microsoft stack. I am using OData for some of my restful services. Recently I came across Swagger for API documentation and I am trying to understand how it relates to OData. Both of them seem to be RESTful specifications. Which one is widely used?
Swagger is a specification for documenting APIs. By creating a swagger document for your API, you can pass it to an instance of Swagger UI, which renders the document in a neat, readable format and provides tooling to invoke your APIs. See the swagger.io website for further information. OData is a specification for cre...
OpenAPI
32,858,371
58
Although I have seen the examples in the OpenAPI spec: type: object additionalProperties: $ref: '#/definitions/ComplexModel' it isn't obvious to me why the use of additionalProperties is the correct schema for a Map/Dictionary. It also doesn't help that the only concrete thing that the spec has to say about additi...
Chen, I think your answer is correct. Some further background that might be helpful: In JavaScript, which was the original context for JSON, an object is like a hash map of strings to values, where some values are data, others are functions. You can think of each name-value pair as a property. But JavaScript doesn't ha...
OpenAPI
41,239,913
58
How to specify a property as null or a reference? discusses how to specify a property as null or a reference using jsonschema. I'm looking to do the same thing with swagger. To recap the answer to the above, with jsonschema, one could do this: { "definitions": { "Foo": { # some complex object } ...
OpenAPI 3.1 Define the property as anyOf of the $ref and type: 'null'. YAML version: foo: anyOf: - type: 'null' # Note the quotes around 'null' - $ref: '#/components/schemas/Foo' JSON version: "foo": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/Foo" } ] } Why us...
OpenAPI
40,920,441
56
Are there any tools/libraries to convert OpenAPI 2.0 definitions to OpenAPI 3.0, without doing it one per row?
Swagger Editor Paste your OpenAPI 2.0 definition into https://editor.swagger.io and select Edit > Convert to OpenAPI 3 from the menu. Swagger Converter Converts OpenAPI 2.0 and Swagger 1.x definitions to OpenAPI 3.0. https://converter.swagger.io/api/convert?url=OAS2_YAML_OR_JSON_URL This gives you JSON. If you want Y...
OpenAPI
59,749,513
56
I have a series of parameters in Swagger like this "parameters": [ { "name": "username", "description": "Fetch username by username/email", "required": false, "type": "string", ...
Mutually exclusive parameters are possible (sort of) in OpenAPI 3.x: Define the mutually exclusive parameters as object properties, and use oneOf or maxProperties to limit the object to just 1 property. Use the parameter serialization method style: form and explode: true, so that the object is serialized as ?propName=...
OpenAPI
21,134,029
54
How to enable "Authorize" button in springdoc-openapi-ui (OpenAPI 3.0 /swagger-ui.html) for Bearer Token Authentication, for example JWT. What annotations have to be added to Spring @Controller and @Configuration classes?
I prefer to use bean initialization instead of annotation. import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import org.s...
OpenAPI
59,898,874
54
I have a POST request that uses the following JSON request body. How can I describe this request body using OpenAPI (Swagger)? { "testapi":{ "testapiContext":{ "messageId":"kkkk8", "messageDateTime":"2014-08-17T14:07:30+0530" }, "testapiBody":{ "cameraServiceRq":{ "osType":"andro...
I made it work with: post: consumes: - application/json produces: - application/json - text/xml - text/html parameters: - name: body in: body required: true schema: # Body schema with atomic property examples ...
OpenAPI
31,390,806
53
In OpenAPI (Swagger) 2.0, we could define header parameters like so: paths: /post: post: parameters: - in: header name: X-username But in OpenAPI 3.0.0, parameters are replaced by request bodies, and I cannot find a way to define header parameters, which would further be used for authenti...
In OpenAPI 3.0, header parameters are defined in the same way as in OpenAPI 2.0, except the type has been replaced with schema: paths: /post: post: parameters: - in: header name: X-username schema: type: string When in doubt, check out the Describing Parameters guide...
OpenAPI
50,117,059
46
I have an Asp.Net web API 5.2 project in c# and generating documentation with Swashbuckle. I have model that contain inheritance something like having an Animal property from an Animal abstract class and Dog and Cat classes that derive from it. Swashbuckle only shows the schema for the Animal class so I tried to play w...
It seems Swashbuckle doesn't implement polymorphism correctly and I understand the point of view of the author about subclasses as parameters (if an action expects an Animal class and behaves differently if you call it with a dog object or a cat object, then you should have 2 different actions...) but as return types I...
OpenAPI
34,397,349
44
I'm writing an OpenAPI definition in Swagger Editor. One of my type definitions contains an array containing child elements of the same type as the parent. I.e. something like this: definitions: TreeNode: type: object properties: name: type: string description: The name of the tree node....
Your definition is perfectly fine. It's a known issue with rendering recursive schemas in Swagger Editor and Swagger UI: https://github.com/swagger-api/swagger-ui/issues/3325 To work around the "Example Value" showing null/"string"/undefined instead of a recursive element, you can add a custom example to your schema: d...
OpenAPI
36,866,035
42
I want to combine an API specification written using the OpenAPI 3 spec, that is currently divided into multiple files that reference each other using $ref. How can I do that?
I wrote a quick tool to do this recently. I call it openapi-merge. There is a library and an associated CLI tool: https://www.npmjs.com/package/openapi-merge https://www.npmjs.com/package/openapi-merge-cli In order to use the CLI tool you just write a configuration file and then run npx openapi-merge-cli. The configu...
OpenAPI
54,586,137
42
I'm preparing my API documentation by doing it per hand and not auto generated. There I have headers that should be sent to all APIs and don't know if it is possible to define parameters globally for the whole API or not? Some of these headers are static and some has to be set when call to API is made, but they are all...
It depends on what kind of parameters they are. The examples below are in YAML (for readability), but you can use http://www.json2yaml.com to convert them to JSON. Security-related parameters: Authorization header, API keys, etc. Parameters used for authentication and authorization, such as the Authorization header, AP...
OpenAPI
19,590,197
41
I'm struggling with the syntax of swagger to describe a response type. What I'm trying to model is a hash map with dynamic keys and values. This is needed to allow a localization. The languages may vary, but english should always be provided. The response would look like this in JSON: { id: "1234", name: { en: ...
Your usage of additionalProperties is correct and your model is correct. additionalProperties In Swagger/OpenAPI, hashmap keys are assumed to be strings, so the key type is not defined explicitly. additionalProperties define the type of hashmap values. So, this schema type: object additionalProperties: type: string ...
OpenAPI
41,097,913
40
I have an existing Spring REST API for which I want to generate the OpenAPI 3.0 YAML file and not Swagger 2.0 JSON/YAML? Since as of now, SpringFox does not support YAML generation. It generates JSON with Swagger 2.0 (which follows OPEN API 3.0 spec). Also, there is https://github.com/openapi-tools/swagger-maven-plugin...
We have used lately springdoc-openapi java library. It helps automating the generation of API documentation using spring boot projects. It automatically deploys swagger-ui to a spring-boot application Documentation will be available in HTML format, using the official [swagger-ui jars]: The Swagger UI page should then b...
OpenAPI
54,921,110
37
I'm trying to build a Swagger model for a time interval, using a simple string to store the time (I know that there is also datetime): definitions: Time: type: string description: Time in 24 hour format "hh:mm". TimeInterval: type: object properties: lowerBound: $ref: "#/definitions/Ti...
TL;DR: $ref siblings are supported (to an extent) in OpenAPI 3.1. In previous OpenAPI versions, any keywords alongside $ref are ignored. OpenAPI 3.1 Your definition will work as expected when migrated to OpenAPI 3.1. This new version is fully compatible with JSON Schema 2020-12, which allows $ref siblings in schemas. o...
OpenAPI
33,629,750
36
I am designing an API and I want to define an enum Severity which can have values LOW, MEDIUM or HIGH. Internally Severity gets stored as an integer so I want to map these to 2,1 and 0 respectively. Is there a way to do this in an OpenAPI definition? This is currently what I have for Severity: severity: type: strin...
OpenAPI 3.1 OpenAPI 3.1 uses the latest JSON Schema, and the recommended way to annotate individual enum values in JSON Schema is to use oneOf+const instead of enum. This way you can specify both custom names (title) and descriptions for enum values. Severity: type: integer oneOf: - title: HIGH const: 2 d...
OpenAPI
66,465,888
34
I'm having a hard time trying to figure out how I can nest models in OpenAPI 2.0. Currently I have: SomeModel: properties: prop1: type: string prop2: type: integer prop3: type: $ref: OtherModel OtherModel: properties: otherProp: type: string I have tried many other ways:...
The correct way to model it in OpenAPI 2.0 would be: swagger: '2.0' ... definitions: SomeModel: type: object properties: prop1: type: string prop2: type: integer prop3: $ref: '#/definitions/OtherModel' # <----- OtherModel: type: object properties: ...
OpenAPI
26,287,962
32
How to define constant string variable in swagger open api 3.0 ? If I define enum it would be like as follows "StatusCode": { "title": "StatusCode", "enum": [ "success", "fail" ], "type": "string" } But enums can be list of values, Is there any way to de...
As @Helen already pointed out, and as you can read in the linked answer, currently it does not seem to get any better than an enum with only one value. Full example that can be pasted into http://editor.swagger.io/: { "openapi": "3.0.0", "info": { "title": "Some API", "version": "Some version" }, "paths...
OpenAPI
51,780,038
32
I have a project (Spring Boot App + Kotlin) that I would like to have an Open API 3.0 spec for (preferably in YAML). The Springfox libraries are nice but they generate Swagger 2.0 JSON. What is the best way to generate an Open Api 3.0 spec from the annotations in my controllers? Is writing it from scratch the only way?...
We have used springdoc-openapi library in our kotlin project, and it meets our need for automating the generation of API documentation using spring boot projects. It automatically deploys swagger-ui to a spring-boot application The Swagger UI page should then be available at: - http://server:port/context-path/swagger-u...
OpenAPI
55,938,207
31
I would like to POST a json body with Swagger, like this : curl -H "Content-Type: application/json" -X POST -d {"username":"foobar","password":"xxxxxxxxxxxxxxxxx", "email": "foo@bar.com"}' http://localhost/user/register Currently, I have this definition : "/auth/register": { "post": { "tags": [ ...
You need to use the body parameter: "parameters": [ { "in": "body", "name": "body", "description": "Pet object that needs to be added to the store", "required": false, "schema": { "$ref": "#/definitions/Pet" } } ], and #/definitions/Pet is d...
OpenAPI
35,411,628
30
I have a yaml specification that has been updated from swagger 2.0 to openapi 3.0.0 The file itself is about 7,000 lines so it is challenging to validate by hand. I need to figure out which tags I have are no longer compatible with openapi 3.0.0. How can I validate my schema? Are there any command line tools I can use?...
Swagger Editor https://editor.swagger.io performs validation on the client side, meaning your definition is not sent anywhere. You can also run the editor locally, e.g. offline. Notes: Because of lazy loading you may need to expand all operations and models in the UI panel to see all of the errors. Warnings are displa...
OpenAPI
60,216,133
30
The API I'm trying to describe has a structure where the root object can contain an arbitrary number of child objects (properties that are themselves objects). The "key", or property in the root object, is the unique identifier of the child object, and the value is the rest of the child object's data. { "child1": { ....
Your example is correct. how do I document what the restrictions are for the "key" in the object? Ideally I'd like to say something like "it's not just any arbitrary string, it's the ID that corresponds to the child". Is this supported in any way? OpenAPI 3.1 OAS 3.1 fully supports JSON Schema 2020-12, including pat...
OpenAPI
46,552,863
28
Using this schema definition: schemas: AllContacts: type: array items: $ref: '#/definitions/ContactModel1' example: - id: 1 firstName: Sherlock lastName: Holmes - id: 2 firstName: John lastName: Watson I get this expected result: [ { "id": 1, ...
This is NOT a valid definition: components: schemas: AllContacts: type: array items: $ref: '#/definitions/ContactModel1' example: Homes: $ref: '#/components/examples/Homes' Watson: $ref: '#/components/examples/Watson' 1) The example syntax is wrong. O...
OpenAPI
49,839,121
28
Is there any way to document the following query? GET api/v1/users?name1=value1&name2=value where the query parameter names are dynamic and will be received from the client. I'm using the latest Swagger API.
Free-form query parameters can be described using OpenAPI 3.x, but not OpenAPI 2.0 (Swagger 2.0). The parameter must have type: object with the serialization method style: form and explode: true. The object will be serialized as ?prop1=value1&prop2=value2&..., where individual prop=value pairs are the object properties...
OpenAPI
49,582,559
27
I want to use Swagger Codegen for OpenAPI 3.0 YAML file. And I see Swagger Codegen 3.0.0-rc0 is available. But when I try to use that I run into issues. Following are the details: My pom.xml file with swagger-codegen plugin: <plugin> <groupId>io.swagger</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId...
To use Swagger Codegen with Maven plug-in for OpenAPI 3.0.0 spec, you may consider using OpenAPI Generator instead (which is a community-driven version of Swagger Codegen). <dependency> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>3.3.4</version> </de...
OpenAPI
49,616,529
27
I recently upgraded my API to a .net core 3.1 server using Swashbuckle 5 with the newtonsoft json nuget, which produces an openapi 3 schema. I then use NSwag to generate a C# API. Previously I had a .net core 2.2 server with swashbuckle 4, producing a swagger 2.0 api schema. I have a generic response class for all res...
There is a setting that accomplishes this: UseAllOfToExtendReferenceSchemas It changes the schema to this, which nswag can use to allow nulls for $ref properties. "payload": { "required": [ "false" ], "allOf": [ { "$ref": "#/components/schemas/MyResultClass" } ], "null...
OpenAPI
62,424,769
27
I noticed that in OpenAPI Path Items and some other constructs you have both summary and description fields, what is the difference between those, and what is the purpose of each? For me, they seem to accomplish the same thing, and I did not find anything about this in the documentation. It might seem like a non-sense ...
summary is short, description is more detailed. Think of the summary as a short one or two sentence explanation of what the intended purpose of the element is. You won't be able to describe all the subtle details, but at a high level, it should be able to explain the purpose of the element. Many documentation tools wil...
OpenAPI
66,936,118
27
Referencing OpenAPI 2.0, Schema Object, or Swagger 2.0, Schema Object, and the definition of discriminator field as: Adds support for polymorphism. The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this s...
According to this google group, discriminator is used on top of the allOf property and it is defined in the super type for polymorphism. If discriminator is not used, the allOf keyword describes that a model contains the properties of other models for composition. Just like in your sample code, Pet is a super type wit...
OpenAPI
39,683,846
26
I am defining an API specification in SwaggerHub using OpenAPI 2.0. The /contacts request returns an array of contacts. The definition is below: /contacts: get: tags: - contacts summary: Get all the contacts description: This displays all the contacts present for the user. opera...
An array of objects is defined as follows. The value of items must be a single model that describes the array items. definitions: AllContacts: type: array items: $ref: '#/definitions/ContactModel' ContactModel: type: object properties: id: type: integer example: 1 ...
OpenAPI
46,167,981
26
I have created a RESTful API, and I am now defining the Open API 3.0 JSON representation for the usage of this API. I am requiring usage of a parameter conditionally, when another parameter is present. So I can't really use either required: true or required: false because it needs to be conditional. Should I just defin...
From the docs: Parameter Dependencies OpenAPI 3.0 does not support parameter dependencies and mutually exclusive parameters. There is an open feature request at github.com/OAI/OpenAPI-Specification/issues/256. What you can do is document the restrictions in the parameter description and define the logic in the 400 Bad ...
OpenAPI
63,209,596
26
I'm writing an OpenAPI spec for an existing API. This API returns status 200 for both success and failure, but with a different response structure. For example, in the signup API, if the user signed up successfully, the API sends status 200 with the following JSON: { "result": true, "token": RANDOM_STRING } An...
This is possible in OpenAPI 3.0 but not in 2.0. OpenAPI 3.0 supports oneOf for specifying alternate schemas for the response. You can also add multiple response examples, such as successful and failed responses. Swagger UI supports multiple examples since v. 3.23.0. openapi: 3.0.0 ... paths: /something: get: ...
OpenAPI
47,447,403
25
I'm looking for some library or example of code to format FastAPI validation messages into human-readable format. E.g. this endpoint: @app.get("/") async def hello(name: str): return {"hello": name} Will produce the next json output if we miss name query parameter: { "detail":[ { "loc":...
FastAPI has a great Exception Handling, so you can customize your exceptions in many ways. You can raise an HTTPException, HTTPException is a normal Python exception with additional data relevant for APIs. But you can't return it you need to raise it because it's a Python exception from fastapi import HTTPException ......
OpenAPI
58,642,528
25